'Cypress: check if new opened tab has correct URL
If I have a link in my website. Eg. <a href="//google.com" target="_blank">go to Google</a> and I want to make a test:
- GIVEN link (html tag
a) - WHEN click the link
- THEN browser opens new tab and URL of this tab includes 'google.com'
I know that this does not work:
cy.get('a').click();
cy.url().should('include', 'google.com');
Solution 1:[1]
Since the a has a target attribute you can do this.
cy.get('a')
.should('be.visible')
.then(($a) => {
expect($a).to.have.attr('target','_blank')
// update attr to open in same tab
$a.attr('target', '_self')
})
.click()
cy.url().should('include', 'google.com')
Depending on your app and what you are wanting to test, using cy.request() and checking on 200 status code may suffice for an external url.
Solution 2:[2]
You can use removeAttr to remove target and then click the link and assert. Something like:
cy.get('a').invoke('removeAttr', 'target').click()
cy.url().should('include', 'google.com')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jjhelguero |
| Solution 2 | Alapan Das |
