gpt4 book ai didi

javascript - 如何在 Jest 单元测试中模拟 "this"关键字

转载 作者:行者123 更新时间:2023-12-01 01:17:47 25 4
gpt4 key购买 nike

我需要使用 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: Cannot read property 'window' of undefined

在这种情况下如何解决“this”关键字的问题?

最佳答案

这里 this.window 是组件属性,可能用作 window 全局的抽象。 componentDidUpdate 内的 this 与测试内的 this 不是同一对象

它可以在组件实例上进行模拟:

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

根据经验,出于可测试性的目的,所有无操作函数都应该是 Jest stub ,因此如果需要,可以稍后断言它们的调用。

关于javascript - 如何在 Jest 单元测试中模拟 "this"关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54568373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com