You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取按钮点击精确时间?验证下载文件名时间匹配问题

解决下载文件名时间秒数偏差的问题

问题原因

你当前的代码是点击按钮后才生成时间戳,但点击操作本身需要一定执行时间,导致生成的时间和按钮实际被点击的时间存在秒级偏差,所以秒数匹配不上。

修正方案

在点击按钮前先记录时间,这样就能保证获取的是按钮点击时刻的近似时间:

// 先记录点击前的时间
const date = new Date();
const exactTime = date.toLocaleTimeString('sv', {hour12: false, timeZone: 'Asia/Jakarta'})

// 再执行点击操作
cy.get('download-button').click()

// 后续验证文件名包含 exactTime 即可
cy.readFile('path/to/downloaded/file').then(file => {
  expect(file.name).to.include(exactTime)
})

额外优化

如果系统时间和前端/服务器时间存在微小差异,可以放宽秒数的匹配条件,比如允许±1秒的误差:

// 获取点击前后的时间范围,覆盖1秒误差区间
const beforeClick = new Date();
cy.get('download-button').click()
const afterClick = new Date(beforeClick.getTime() + 1000);

// 生成时间范围的字符串形式
const timeBefore = beforeClick.toLocaleTimeString('sv', {hour12: false, timeZone: 'Asia/Jakarta'})
const timeAfter = afterClick.toLocaleTimeString('sv', {hour12: false, timeZone: 'Asia/Jakarta'})

// 验证文件名时间在这个范围内
cy.get('downloaded-file').then(file => {
  const fileNameTime = file.name.match(/(\d{2}:\d{2}:\d{2})/)[1]
  expect(fileNameTime).to.be.oneOf([timeBefore, timeAfter])
})

内容的提问来源于stack exchange,提问作者krisc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 22:36:19