Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 916
davidk Avatar asked May 18 '18 13:05

davidk


People also ask

How to keep Cypress focused on a test?

Your best bet here is to keep Cypress focused when working on a test. .focus () requires being chained off a command that yields DOM element (s). .focus () requires the element to be able to receive focus.

Why can't I call focus () on an element in Cypress?

If there is currently a different DOM element with focus, Cypress issues a blur event to that element before running the .focus () command. Ensure the element you are trying to call .focus () on is a focusable element. If you see this error, you may want to ensure that the main browser window is currently focused.

What does it mean when Cypress blur in debug mode?

This means not being focused in debugger or any other window when the command is run. Internally Cypress does account for this, and will polyfill the blur events when necessary to replicate what the browser does.

How to change the default behavior of a cypress window?

Pass in an options object to change the default behavior of cy.window (). If the application sets a custom property, like: Our test can confirm the property was properly set. Note: Cypress commands are asynchronous, so you cannot check a property value before the Cypress commands ran. Instead, use cy.then () callback to check the value.


1 Answers

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

like image 115
bkucera Avatar answered Nov 15 '22 00:11

bkucera