How to Stub Window Methods in Cypress

How to Stub Window Methods in Cypress

Ferenc Almasi β€’ 2021 October 28 β€’ Read time 1 min read
  • twitter
  • facebook

To stub window methods in Cypress, we can use the cy.stub command passing the window object with the method we want to stub, eg.:

Copied to clipboard!
cy.visit('https://cypress.io').then(window => {
    cy.stub(window, 'open').as('open');
});

Make sure you use cy.stub only after a page is visited, otherwise you will not have access to the window object. We can use an alias to later reference the stubbed method in the following way:

Copied to clipboard!
cy.get('.open').click();

// Reference the stubbed and aliased window.open method
cy.get('@open').should('have.been.calledOnce');

If you also want to add extra properties on the window object and make it available across all spec files, we can use a before hook that you can define in your support/index.js file:

Copied to clipboard! Playground
before(() => {
    window.app = { ... }
});

// Now window.app is globally available throughout your test suite
it('Should visit the home page', () => {
    cy.visit(app.home);
});

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to Stub Window Methods in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.