Prahlad Shrestha
wesionaryTEAM
Published in
2 min readAug 2, 2022

--

HANDLING NEW BROWSER TAB AND WINDOW IN CYPRESS

As we know cypress does not allow handling of new browser tabs and windows by default. Cypress has mentioned this in the automation restrictions section of their documentation. In this article, we will be discussing how can we handle this problem with a simple way around.

Handling New Tab

In cypress, when we click a button or a link that opens a new browser tab, cypress opens the new tab. But we can not continue our test in the new browser tab, cypress is unable to do so. Because Cypress runs in the browser, it will never have multi-tabs support. We know that it is triggered by the target="_blank" attribute. If we need to test if the new tab do open or not then we can simply do this:

cy.get('a[href="/foo"]').should('have.attr', 'target', '_blank')

Or if we need to continue the test on the newly opened tab, we can simply remove the target="_blank" attribute and open the link on the same page. So let’s try to handle this using the example.

When we use invoke('removeAttr','target) and click on the button or link, the link will be opened on the same tab and we can continue our test.

Handling New Window

Just like with multiple tabs — Cypress does not support controlling more than one open browser at a time. So let’s try to handle this using the example.

First, we get the Window object and then we replace the window.open() function with an arrow function. After that, we will change the window location win.location.href to be the same as the new window URL. Then we create an alias for the same openWindow which we will use later to make an assertion. Then let’s click the button, which triggers javascript’s window.open()call. We will make an assertion to make sure that window.open() is triggered when a button is clicked by cy.get('@popup').should(“be.called"). After that new URL will be opened on the same tab and we can continue our test.

Result

--

--