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

问题描述 投票:0回答:1

我需要使用Jest单元测试来编写此代码:

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

使用测试用例:

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();
  });

但是,我得到了错误:

TypeError:无法读取未定义的属性“窗口”

在这种情况下,如何使用“ this”关键字解决此问题?

javascript reactjs unit-testing this jestjs
1个回答
2
投票

此处this.window是组件属性,很可能用作全局window的抽象。 this中的componentDidUpdate与测试中的this是不同的对象

可以在组件实例上模拟:

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

根据经验,出于测试目的,所有无操作功能都应为Jest存根,因此,如果需要,可以稍后声明它们的调用。

© www.soinside.com 2019 - 2024. All rights reserved.