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

Cypress中使用外部JSON作为POST请求Payload时如何动态设置日期戳

在Cypress中使用外部JSON作为Payload并动态设置日期字段

解决方案

加载外部JSON fixture后,在发送POST请求前直接修改from和to字段的值,替换为当日的Unix时间戳即可。具体实现如下:

完整代码示例

cy.fixture('createUsers.json').then((requestBody) => {
  // 计算当日起始时间的Unix时间戳(与你现有实现逻辑一致)
  const testDate = Date.parse(new Date().toLocaleDateString("en-US"));
  
  // 动态覆盖JSON文件中的from和to字段
  requestBody.from = testDate;
  requestBody.to = testDate;

  cy.request('POST', '/api/vi/createUsers', requestBody).then(function (res) {
    localStorage.setItem('token', res.body.token);
    localStorage.setItem('refreshToken', res.body.refreshToken);
  });
});

关键说明

  • Cypress的cy.fixture()会将JSON文件解析为普通JavaScript对象,因此可以直接修改其属性值。
  • 这种方式既保留了JSON文件中静态字段的可维护性,又实现了动态字段的需求。
  • 若需在多个测试用例中复用时间戳计算逻辑,可封装为Cypress命令:
    // 在cypress/support/commands.js中添加
    Cypress.Commands.add('getCurrentDayTimestamp', () => {
      return Date.parse(new Date().toLocaleDateString("en-US"));
    });
    
    // 测试用例中调用
    cy.fixture('createUsers.json').then((requestBody) => {
      cy.getCurrentDayTimestamp().then(testDate => {
        requestBody.from = testDate;
        requestBody.to = testDate;
        cy.request('POST', '/api/vi/createUsers', requestBody).then(res => {
          localStorage.setItem('token', res.body.token);
          localStorage.setItem('refreshToken', res.body.refreshToken);
        });
      });
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 04:35:05