Dvir
Dvir

Reputation: 97

Cypress - mocking window property

I have a code that uses window.foo.abc as a condition to display something.

I want to test this functionality with cypress and I want to mock this value to be false and true.

How can I do that?

I've tried

 before(function() {
      Cypress.on('window:before:load', win => {
        win.foo.abc = true;
      });

and

  cy.window().then(win => {
    window.foo.abc = true;
  });

with no success.

How can I mock this value?

thanks 🙏

Upvotes: 2

Views: 5676

Answers (1)

Fody
Fody

Reputation: 32118

This code is incorrect,

Cypress.on('window:before:load', win => {
  window.foo.abc = true;
});

It should be

Cypress.on('window:before:load', win => {
  win.foo.abc = true;
});

You don't have to use it in before(), but it should be at the top of the spec.

But I suspect it still won't work after correcting, most likely the app resets foo to a new object during loading, i.e during cy.visit()

You can use the 2nd block

cy.visit('...')  // visit before changing

cy.window().then(win => {
  win.foo.abc = true;            // correct the syntax here as well
})

Upvotes: 5

Related Questions