How to Stub Window Methods in Cypress
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.:
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:
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:
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:
Resources:
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: