在我的 Cypress 测试中,我有一个包含日期的字段,我希望它对于测试运行日期是动态的。
我尝试这样处理:
export const interceptGetEntity = () => {
cy.intercept('GET', 'my/api/entities/123145',
(req) => {
cy.fixture('get-entity').then((entity: Entity) => {
const now = new Date();
const thisMonth = now.getMonth();
const thisYear = now.getFullYear();
entity.steps.forEach((step, index) => {
step.effectiveDate = formatDateString(new Date(thisYear, thisMonth + index, 1));
})
req.reply(entity);
});
}).as('getEntity');
};
但是后来我得到了这个错误:
Cypress 检测到您从命令返回了承诺,同时还 在该承诺中调用一个或多个 cy 命令。
返回承诺的命令是:
cy.wait()
您在 Promise 中调用的 cy 命令是:
cy.fixture()
因为 Cypress 命令已经是 Promise 式的,所以你不需要 包裹它们或返回您自己的承诺。
Cypress 将用最终的 Cypress 来解决您的命令 命令产生。
这是错误而不是警告的原因是 Cypress 内部按顺序排列命令,而 Promise 会立即执行 当它们被调用时。尝试协调这一点将阻止 柏树从永远解决。了解更多
显然,我不想将这种逻辑应用于每个测试,而是希望将其放在一个公共位置。 有更好的方法来操作我的夹具数据吗?
找到了一个简单的同步解决方法
代替:
(req) => {
cy.fixture('get-entity').then((entity: Entity) => {
const now = new Date();
const thisMonth = now.getMonth();
const thisYear = now.getFullYear();
entity.steps.forEach((step, index) => {
step.effectiveDate = formatDateString(new Date(thisYear, thisMonth + index, 1));
})
req.reply(entity);
});
}
我只是使用简单的
require
: 从文件中获取 JSON
(req) => {
const entity = require('../../../fixtures/get-entity.json');
const now = new Date();
const thisMonth = now.getMonth();
const thisYear = now.getFullYear();
entity.steps.forEach((step, index) => {
step.effectiveDate = formatDateString(new Date(thisYear, thisMonth + index, 1));
})
req.reply(entity);
}