Handle New Tabs in Cypress Tests

| 1 min read

This post walks through how to handle Cypress tests which click on links/buttons that opens in a new tab of the same domain.

Examples of links which opens /about in new tabs:

For HTML _blank Links

If the link is a standard HTML ancor tag which uses target="_blank" you can amend the element HTML to use target="_self instead so the link will open in the same tab. You can do this by using the code below.

const setAncorTargetToSelf = (target) => {
  cy.get(target).invoke('attr', 'target', '_self')
}

This function can then be called within a test like below.

it('should set target to _self then click', () => {
  cy.visit('/posts/handle-new-tabs-in-cypress-tests/')

  setAncorTargetToSelf('#html-link')
  cy.get('#html-link').click()

  cy.url().should('contain', '/about')
})

For Javascript window.open Links

If the new tab opening is handled by Javascript window.open instead of HTML you can stub this action to be replace with window.location.href. Below is an example function doing this.

export const stubWinOpenAsWinLocation = () => {
  cy.window().then((window) => {
    cy.stub(window, 'open').callsFake((url) => {
      window.location.href = Cypress.config().baseUrl + url
    })
  })
}

This will need to be called just before your test clicks the link. The test below clicks.

it('should override opening new tab to current window', () => {
  cy.visit('/posts/handle-new-tabs-in-cypress-tests/')

  stubWinOpenAsWinLocation()
  cy.get('#js-link').click()

  cy.url().should('contain', '/about')
})