简体   繁体   English

Cypress - 模拟窗口属性

[英]Cypress - mocking window property

I have a code that uses window.foo.abc as a condition to display something.我有一个使用 window.foo.abc 作为条件来显示某些内容的代码。

I want to test this functionality with cypress and I want to mock this value to be false and true.我想用 cypress 测试这个功能,我想把这个值模拟为 false 和 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.您不必在before()使用它,但它应该位于规范的顶部。

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()但我怀疑它在更正后仍然无法工作,很可能应用程序在加载期间将foo重置为新对象,即在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
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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