Handling a New/Child Tab in Cypress

Waris Jamal
3 min readJun 8, 2022

--

Cypress has some shortcomings and this article will discuss one of them. The architecture has been designed that way to avoid flaky automation tests and provide consistent results. Therefore, Cypress does not support child tabs.

We often open child tabs when we click on a particular link element (anchor tag) and this link has a target="_blank"attribute. This opens a new tab within the same browser window.

TEST CASE:

  1. Go to http://techedclasses.in/
  2. Reach to Notes > Class X
  3. Click on the YouTube link. This opens a new Tab.

It’s very easy to operate the DOM with Cypress, so the same technique we will employ to resolve this issue. Therefore, the issue will be resolved if we remove target="_blank" before clicking on the desired link. So now we first look at the issue that we will face after running this test script.

Test Runner window with issue:

In the above screenshot, you can see that a new tab opens within the same window after clicking on the link, and Cypress does not have access to the new tab, hence we can’t even validate any scenario.

Solution:

cy.get('p a').first().invoke('removeAttr','target').click();

Using the command cy.get('p a')we can get the element and first() allows us to select the first anchor available on the page. The main part is to invoke the jquery method with the attribute name removeAttr and the target name by using invoke('removeAttr','target'), then perform a click operation with click().

Now the child tab will open inside the parent tab, and if you want to return to the same URL you can use the following command.

cy.go('back');

Note: In this test case, you will see a cross origin error, as we’re redirecting from http://techedclasses.in/ to https://www.youtube.com/, which is also a disadvantage of Cypress up to version 9.6.0, however the flow of the child tabs is not affected.

Conclusion

Those who use other automation tools have found that working in child tabs is relatively easy. Managing child tabs in Cypress is a bit challenging as native support is not available. We can easily manage child tabs by following the instructions given in this article, avoiding unnecessary R&D, and saving a lot of time. Feel free to leave a comment if you found it useful.

--

--