我正在处理链式请求,需要等待直到满足条件,这样我才能测试响应。先前的请求总是会返回一个响应,但我需要它的状态是“完成”,有时它是“正在进行”。我不想对这个cy.wait()使用静态等待,因为这要么会使测试变得古怪,要么将永远持续下去。我该怎么做?到目前为止,这是我的代码,但是它会被卡住,永远不会完成。对于静态等待(没有循环),它运行得很好。
有什么想法吗?
it('name of the test', function() {
cy.processFile().then((response) => {
let i=0;
while (i<5){
cy.wait(1000);
cy.getInfo().then((resp) => {
if(resp.body.status !== 'finished'){
i++;
} else {
i = 5;
expect(.....);
}
})
}
})
})发布于 2021-09-06 23:41:11
while (i<5) {语句是同步的,甚至在测试开始之前它会运行五次迭代。
相反,这应该有效。
function waitForStatus (status, count = 0) {
if (count === 5) {
throw 'Never finished'
}
return cy.getInfo().then(resp => {
if (resp.body.status !== status) {
cy.wait(1000) // may not need to wait
waitForStatus(status, ++count) // run again, up to 5 times
} else {
return resp // in case you want to expect(resp)...
}
})
}
cy.processFile().then((response) => {
waitForStatus('finished').then(resp => {
expect(resp)...
})
})这里有一个更详细的信息,编写柏树递归函数。
您的场景
npm i -D cypress-recurse
# or use Yarn
yarn add -D cypress-recurseimport { recurse } from 'cypress-recurse'
it('waits for status', () => {
cy.processFile().then((response) => {
recurse(
() => cy.getInfo(),
(resp) => resp.body.status === 'finished',
{
log: true,
limit: 5, // max number of iterations
timeout: 30000, // time limit in ms
delay: 1000 // delay before next iteration, ms
},
)
.then(resp => {
expect(resp)...
})
})https://stackoverflow.com/questions/69077225
复制相似问题