此代码等待响应并在响应到达后执行操作。 等待超时时我该如何做事?
cy.wait('@login').then((interception) => {
const token = interception.response.body.token
Cypress.env('ACCESS_CODE', token)
});
在 Cypress 中实现这一点是不可能的,如果不进行一些操作来绕过
cy.wait()
并不真正支持条件结果这一事实。
但是,我们可以使用 cy.get()
cy.intercept('/foo').as('foo');
// Cypress code that triggers the `/foo` call
cy.get('@foo.all').then((foo) => {
if (foo.length > 0) {
// code to do if the call is made
} else {
// code to do if the call is not made
}
});
但是,cy.get('@alias.all')
没有任何等待或重试机制,因此如果调用被触发但在调用
cy.get()
之前尚未完成,则该调用可能不会出现在yield数组中。如果是这样的话,
我们可以吞下赛普拉斯的错误。
cy.on('fail', (err, runnable) => {
if (err.message.includes('route: `foo`')) { // check the error message
// code to execute if call is not made
return false // returning false makes sure the test does not fail at this step
}
throw err // throw the error if we don't return false earlier, to ensure other test failures are still raised
})
两件重要的事情:
cy.on()
而不是
Cypress.on()
会将事件的更改限制为仅 特定测试。如果您想在整个测试套件中实现这一点,您需要在支持文件中执行此操作并使用
Cypress.on()
。
return false
/
throw err
-> 包含这些,以便您的测试不会因指定的失败而失败,但会因意外的失败而失败。
不要执行其中任何一项。它们是可能的,但理想的解决方案是以决定性且可重现的方式编写测试或应用程序。 (在理想的测试中,)是否拨打电话不应该存在不确定性。如果这是联系第三方资源,我可能会建议存根或模拟整个流程以消除这种歧义,并对第三方和您的应用程序之间的集成进行其他集中测试。