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.

  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.

  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: