赛普拉斯如何聆听全球事件

赛普拉斯如何聆听全球事件

本文介绍了赛普拉斯如何聆听全球事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个应用程序,它会定期轮询服务器,直到任务完成为止.我们触发一个全局事件,以便赛普拉斯可以捕获并确定任务是否完成,但是在赛普拉斯上使用 document.addEventListener 时遇到了麻烦.这是我们正在做的:

We have an application that polls the server periodically until a task is completed. We fire a global event so that Cypress can catch and find out if the task is finished but we had trouble using document.addEventListener on Cypress. Here's what we're doing:

document.addEventListener('queryEnd', () => {
    cy.get('.chart').should('be.visible')
    cy.get('.table').should('be.visible')
  })

但是;当我们在规范中使用它时,它无法正常工作,我们也无法捕获它.此外,赛普拉斯不等待测试,而是在不等待回调运行的情况下运行 afterEach .

However; when we use it in a spec, it doesn't work expected and we're not able to catch it. Also, Cypress doesn't wait for the test and runs afterEach without waiting for the callback to run.

推荐答案

代码无法正常运行的原因是因为在Cypress中,您的测试运行于与被测应用程序(AUT)不同的框架中.您正在等待的事件将永远不会在赛普拉斯的文档内部触发.

The reason why your code isn't working like you expect is because in Cypress, your tests run in a separate frame than your application under test (AUT). The event you're waiting for will never fire inside of Cypress's document.

要获取AUT的 document ,请使用 cy.document() 像这样:

To get the document of the AUT, use cy.document() like this:

cy.document()
.then($document => {
  // now $document is a reference to the AUT Document
  $document.addEventListener(...)
})

要让赛普拉斯在继续之前等待事件,可以将其包装在 Cypress.Promise 中.赛普拉斯文档中有一个有关等待Promise完成的示例.对于您的 queryEnd 事件,它看起来像这样:

To make Cypress wait for your event before continuing, you can just wrap it in a Cypress.Promise. The Cypress docs have an example about waiting for a Promise to complete. For your queryEnd event, it would look something like this:

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')
})

这篇关于赛普拉斯如何聆听全球事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!