简体   繁体   中英

How to emulate window focus lost in Cypress.io

I am writing E2E tests for a website using Cypress.io. One of the features I would like to test is that the site correctly detects focus lost and displays an (angular material) dialog box. The issue I am having is that I can not find a reliable way to trigger the window focus loss to occur in the testing environment. I have looked at the documentation for various focus and blur events in Cypress.io but am coming up empty. Does anyone know if it is possible to programmatically trigger a window focus loss (blur) from Cypress.io and if so is there documentation or examples I could follow?

It depends on how your page is listening for this event, so there's a few potential solutions:

Try:

cy.window().trigger('blur')

If that doesn't work, try:

cy.document().then((doc) => {
  cy.stub(doc, "hidden").value(true)
})
cy.document().trigger('visibilitychange')

In some cases

I had the same question and the approved answer didn't work for me. But the code below is fine

cy.document().then((doc) => {
  cy.stub(doc, "visibilityState").value("hidden") //or "visible" if you want focus
})
cy.document().trigger('visibilitychange')

after this test other tests fail

cy.document().then((doc) => {
 cy.stub(doc, "visibilityState").value("hidden") 
})
cy.document().trigger('visibilitychange')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM