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
相关产品推荐
相关产品推荐

