When dealing with Deal with Second Tab in Cypress there might be an application edge case. Instead of window.open(url)
the application might create a new window
object and navigate by setting its location
property. This is a valid syntax, see Dev docs.
1 | // notice the first argument is an empty string instead of URL |
This blog post shows how to test this situation using Cypress test runner. First, you need to stub the window.open
method before the application calls it.
1 | // our own object we will return to the application |
🎁 You can find the full source code in my "Stub window.open" recipes at glebbahmutov.com/cypress-examples website.
Now that the stub is set, we can click on the button.
1 | cy.contains('button', 'Open window').click() |
If we know all expected arguments, we can write a precise assertion
1 | cy.get('@open').should( |
If we know only some expected arguments, we can use Sinon match placeholder. For example, if we only know the third argument to be a string:
1 | cy.get('@open').should( |
We can even write a more complex logic to verify individual arguments
1 | cy.get('@open') |
If you want to verify the parsed width and height, capture the numbers using a regular expression. Let's confirm the popup's width is between 250 and 350 pixels.
1 | cy.get('@open') |
Let's confirm the application sets the window's location
property. Since we returned the local variable to an empty object, we can confirm it receives a property.
1 | cy.wrap(winProxy).should( |
By the way, the above syntax retries. Let's say the application set the location
property after a delay. Imagine the following application:
1 | <button id="open">Open window</button> |
The following test retries and passes after 1.5 second pause
1 | // our own object we will return to the application |
Very nice. For more advice on dealing with 2nd window / tab in Cypress tests, read my Deal with Second Tab in Cypress.