在 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);
});
Run Code Online (Sandbox Code Playgroud)
dwe*_*lle 12
while循环;assert.isTrue在 cy 命令之外......)和异步工作(cy 命令)。阅读cypress #Chains-of-Commands 简介resp.something值,如果失败,则整个命令都会失败,因此不再重试。awaitcypress 命令(无论如何您都没有这样做),因此您需要recursion,而不是iteration。换句话说,你不能使用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();
});
Run Code Online (Sandbox Code Playgroud)
如果您不希望 cypress 在重试期间记录所有失败的期望,请不要使用expect/ assertwhich throws,并进行定期比较(并且可能仅在.then链接到最后一次makeRequest()调用的回调中的最后断言)。
| 归档时间: |
|
| 查看次数: |
4450 次 |
| 最近记录: |