← Back to library
Cypressnetworkadvancedv10+

Stub window.open to prevent new tabs

Replace window.open with a cy.stub() so no real tab opens during tests, then assert the call.

1it('share button calls window.open with the correct URL', () => {
2  cy.visit('/share');
3
4  cy.window().then((win) => {
5    // Replace window.open before the button click — no real tab will open
6    cy.stub(win, 'open').as('windowOpen');
7  });
8
9  cy.get('[data-testid="share-btn"]').click();
10
11  // Assert window.open was called with a URL matching the pattern
12  cy.get('@windowOpen').should(
13    'have.been.calledWith',
14    Cypress.sinon.match(//share?id=/),
15    '_blank'
16  );
17});
#window.open#stub#new tab#sinon#spy