我需要使用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”关键字解决此问题?
此处this.window
是组件属性,很可能用作全局window
的抽象。 this
中的componentDidUpdate
与测试中的this
是不同的对象
可以在组件实例上模拟:
const component = mount(<MyComponent {...props} />);
component.instance().window = { FB: {
XFBML: {
parse: jest.fn()
}
} };
根据经验,出于测试目的,所有无操作功能都应为Jest存根,因此,如果需要,可以稍后声明它们的调用。