在 Cypress 测试中,我需要通过调用外部 API 来验证操作。 API 调用将始终返回结果(来自之前的某些运行),因此我不能简单地调用一次并验证结果。我需要重试几次,直到找到当前运行的匹配项并出现总体超时/失败。获得当前结果所需的时间差异很大;我真的不能在这个电话之前疯狂地等待那么久。
请参阅下面片段中的评论;一旦我在循环中尝试请求,它就永远不会被调用。我使用 cy.wait 得到了相同的结果。我也不能将实际请求包装在另一个返回 Cypress.Promise
或类似函数中,这只会将问题推到一个堆栈帧上。
Cypress.Commands.add("verifyExternalAction", (someComparisonValue) => {
const options = {
"url": some_url,
"auth": { "bearer": some_apikey },
"headers": { "Accept": "application/json" }
};
//// This works fine; we hit the assertion inside then.
cy.request(options).then((resp) => {
assert.isTrue(resp.something > someComparisonValue);
});
//// We never enter then.
let retry = 0;
let foundMatch = false;
while ((retry < 1) && (!foundMatch)) {
cy.wait(10000);
retry++;
cy.request(options).then((resp) => {
if (resp.something > someComparisonValue) {
foundMatch = true;
}
});
}
assert.isTrue(foundMatch);
});
最佳答案
- 您不能在 cy 命令之外混契约(Contract)步(
while
循环;assert.isTrue
...)和异步工作(cy 命令)。阅读 introduction to cypress #Chains-of-Commands - 您的第一个请求是断言
resp.something
值,如果失败,则整个命令都会失败,因此不再重试。 - 您正在执行异步工作,并且无法
等待
cypress 命令(无论如何您都没有这样做),因此您需要递归,而不是迭代。换句话说,你不能使用while
循环。
像这样的东西应该有效:
Cypress.Commands.add("verifyExternalAction", (someComparisonValue) => {
const options = {
"url": some_url,
"auth": { "bearer": some_apikey },
"headers": { "Accept": "application/json" }
};
let retries = -1;
function makeRequest () {
retries++;
return cy.request(options)
.then( resp => {
try {
expect( resp.body ).to.be.gt( someComparisonValue );
} catch ( err ) {
if ( retries > 5 ) throw new Error(`retried too many times (${--retries})`)
return makeRequest();
}
return resp;
});
}
return makeRequest();
});
如果您不希望 cypress 在重试期间记录所有失败的期望,请不要使用抛出的 expect
/assert
,并进行常规比较(并且可能仅在链接到最后一个 makeRequest()
调用的 .then
回调末尾断言)。
关于Cypress 请求重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54079106/