简体   繁体   中英

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 => {
        window.foo.abc = true;
      });

and

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

with no success.

How can I mock this value?

thanks 🙏

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, ie during cy.visit()

You can use the 2nd block

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM