Deal with Second Tab in Cypress

How to handle the web application opening a new tab or browser window when running inside Cypress test.

Sometimes your application wants to open a new tab or a new browser window. Cypress injects its spec into the first window, thus it "loses" your application and cannot control the second tab. How to handle this case depends on how the application opens the second tab. Here are links to the solutions:

  1. Anchor link with target

If your application contains a link element like <a href="..." target="_blank">, see Deal with target=_blank. The test can remove the target attribute or change it to _self before clicking. If the href is a mailto:... link, watch the video Test Mailto HREF Anchor Links to see how to validate it.

  1. window.open

If the application calls window.open(url) which opens 2nd tab, the test can stab the window.open method. See Deal with window.open answer and watch 📺 Test window.open Example. If the parent window is checking window.closed to be notified when the user closes the child window/tab, there is a solution, read the blog post Test Child Window Closed Scenario. If you need to open the second window for real and check its contents, and even close it, watch 📺 Check Text And Then Close The 2nd Child Window From Cypress Test.

  1. window.location.replace

Perhaps the toughest case to deal with is when the application uses location.replace to load new URL. While this call does not open the 2nd tab, the application might navigate to another domain, where Cypress loses it. This browser API method cannot be stubbed directly, see Deal with window.location.replace on how to handle this scenario from Cypress test.

  1. Running two Cypress instances

Sometimes your might want to run 2 Cypress instances to test a chat web application for example. In general, I think this is NOT necessary. Instead you can simulate the second user separately, while testing the page interface from Cypress. See my blog posts on this topic:

  1. Form submit

If the second window is opened by the form.submit, see the blog post Stub The Form That Opens The Second Browser Tab which offers several different workarounds.