This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Dilpreet Johal
In this post, we will learn how to handle new tab in Cypress. By default, new tabs are not supported by Cypress, we will take a look at a workaround to solve this issue.
Why Cypress doesn't support second tab?
Cypress tests runs within a browser and because of that it injects the tests into a first window / tab; anything else outside of the tab, Cypress does not have access to it.
This was a design decision by the Cypress team and they will never support multiple tabs even in future.
How to handle new tab in Cypress?
Alright, so we understand that Cypress doesn't support new tabs but what if your application opens links in new tab then how do you handle such case? Well we will need to do some workaround to get this to work.
First, it's important to understand how the website is opening the second tab? These are 2 of the common ways -
- using
target="_blank"
attribute (most common) - using JavaScript redirect
Handling the target
attribute
<a href="/contact" target="_blank" role="button" id="contact-us">
When a browser sees target="_blank"
on a link, it automatically knows to open the link in a new tab. We can use this to our advantage and remove the target
attribute from the link and then the browser will open the link in the same tab.
it('Handling new tab', () => {
cy
.get('#contact-us')
.invoke("removeAttr", "target")
.click() // will open the contact page in a new tab
cy.get("h1").should("have.text", "Contact");
})
We are using the invoke
method to remove the target
attribute from the link element which triggers the browser to open the link within the same tab.
Handling JavaScript redirect
For JavaScript redirects, you will need to understand how the redirect is being done and based on that implement a solution for it. This is a good link to refer to by Gleb Bahmutov which provides various solutions to handle such scenarios.
To learn more about how to handle new tab in Cypress, check out the video below –
📧 Subscribe to my mailing list to get access to more content like this as well as be part of amazing free giveaways.
đź‘Ť You can follow my content here as well -
...
I love coffees! And, if this post helped you out and you would like to support my work, you can do that by clicking on the button below and buying me a cup of coffee -
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Dilpreet Johal
Dilpreet Johal | Sciencx (2022-09-19T12:04:24+00:00) Handling new tab in Cypress. Retrieved from https://www.scien.cx/2022/09/19/handling-new-tab-in-cypress/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.