我们有一个应用程序,它会定期轮询服务器,直到任务完成为止。我们触发一个全局事件,以便赛普拉斯可以捕获并确定任务是否完成,但是在赛普拉斯上使用document.addEventListener
时遇到了麻烦。这是我们正在做的:
document.addEventListener('queryEnd', () => {
cy.get('.chart').should('be.visible')
cy.get('.table').should('be.visible')
})
但是;当我们在规范中使用它时,它无法正常工作,我们也无法捕获它。此外,赛普拉斯不等待测试,而是在不等待回调运行的情况下运行afterEach
。
答案 0 :(得分:3)
代码无法正常运行的原因是因为在赛普拉斯中,测试在与被测应用程序(AUT)不同的框架中运行。您正在等待的事件将永远不会在赛普拉斯的document
内部触发。
要获取AUT的document
,请像这样使用cy.document()
:
cy.document()
.then($document => {
// now $document is a reference to the AUT Document
$document.addEventListener(...)
})
要使赛普拉斯在继续之前等待事件,可以将其包装在Cypress.Promise
中。赛普拉斯的文档中有一个有关waiting for a Promise to complete的示例。对于您的queryEnd
事件,它看起来像这样:
cy.document() // get a handle for the document
.then($document => {
return new Cypress.Promise(resolve => { // Cypress will wait for this Promise to resolve
const onQueryEnd = () => {
$document.removeEventListener('queryEnd', onQueryEnd) // cleanup
resolve() // resolve and allow Cypress to continue
}
$document.addEventListener('queryEnd', onQueryEnd)
})
})
.then(() => {
cy.get('.chart').should('be.visible')
cy.get('.table').should('be.visible')
})