简体   繁体   English

如何在 Jest 单元测试中模拟“this”关键字

[英]How to mock "this" keyword in Jest Unit Testing

I need to this code using Jest Unit Testing:我需要使用 Jest 单元测试这个代码:

componentDidUpdate(prevProps) {
    if (prevProps.socialMediaId !== this.props.socialMediaId) {
      if (typeof this.window.FB !== 'undefined') {
        this.window.FB.XFBML.parse();
      }
    }
  }

using the test case:使用测试用例:

it('should test componentDidUpdate', () => {
    props.socialMediaId = '/old_id/';
    const component = mount(<MyComponent {...props} />);
    this.window.FB = {
      XFBML: {
        parse: () => {}
      }
    };
    props.socialMediaId = '/new_id/';
    component.setProps(props);
    expect(this.window.FB.XFBML.parse).toHaveBeenCalled();
  });

But, I'm getting the error:但是,我收到错误:

TypeError: Cannot read property 'window' of undefined类型错误:无法读取未定义的属性“窗口”

How to fix this issue with " this " keyword in this case?在这种情况下,如何使用“ this ”关键字解决此问题?

Here this.window is component property that is likely used as an abstraction over window global.这里this.window是组件属性,可能用作window全局的抽象。 this inside componentDidUpdate isn't the same object as this inside a test this里面的componentDidUpdate与测试中的this不是同一个对象

It can be mocked on component instance:它可以在组件实例上模拟:

const component = mount(<MyComponent {...props} />);
component.instance().window = { FB: {
  XFBML: {
    parse: jest.fn()
  }
} };

As a rule of thumb, all no-op functions should be Jest stubs for testability purposes, so their calls could be asserted later if needed.根据经验,为了可测试性目的,所有无操作函数都应该是 Jest 存根,因此如果需要,可以稍后断言它们的调用。

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

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