Cypress: check if new opened tab has correct URL

Viewed 1348

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');
2 Answers

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.

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')
Related