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

如何在Cypress.Commands()中动态设置今日相关日期?

解决Cypress自定义命令中动态日期生效问题

问题根源

你之前传入(new Date().getDate() - 1)只返回了日期的日部分数字(比如今日是7号则返回6),并非命令所需的完整日期字符串(如2023-08-06),格式不匹配导致未生效。

解决方案

1. 编写日期格式化工具函数

先实现一个能生成指定偏移天数的标准日期字符串的函数,默认返回"今日-1天"(昨天)的YYYY-MM-DD格式:

// 在cypress/support/commands.js中添加
const getOffsetDate = (offsetDays = -1) => {
  const targetDate = new Date();
  targetDate.setDate(targetDate.getDate() + offsetDays);
  // 补零处理确保月份、日期为两位数
  const year = targetDate.getFullYear();
  const month = String(targetDate.getMonth() + 1).padStart(2, '0');
  const day = String(targetDate.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

2. 修改自定义命令,设置默认动态日期

更新cy.create123命令,让起始日期参数默认调用上述函数,同时保留传入自定义日期的能力:

Cypress.Commands.add('create123', (startDate = getOffsetDate(), endDate) => {
  // 替换为你的命令原有逻辑,比如输入日期到表单
  cy.get('[data-testid="start-date"]').type(startDate);
  if (endDate) {
    cy.get('[data-testid="end-date"]').type(endDate);
  }
  // 其他操作步骤...
});

3. 调用方式

  • 自动使用"今日-1天"作为起始日期:
    cy.create123();
    
  • 自定义起始日期(比如今日+30天):
    cy.create123(getOffsetDate(30), '2023-08-07');
    

注意事项

  • 日期格式化必须匹配目标输入框的格式要求(如果你的系统用MM/DD/YYYY,调整工具函数的拼接逻辑即可)
  • 该工具函数是同步执行的,无需用Cypress异步命令包裹,直接在自定义命令中调用即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:16:58