使用Jest和React,我如何监视一个this.setState()
并测试功能hasBeenCalled()
it('shall update targets when engine register has been called', () =>
{
const wrapper = shallow(
<LazyloadProvider>
<p>Wow</p>
</LazyloadProvider>
).instance();
expect(wrapper.state.targets).toEqual({}); // pass
wrapper.engine.register(FIXTURE.REACT_REF); // pass
expect(wrapper.state.targets).not.toEqual({}); //pass
expect(wrapper.setState).toHaveBeenCalled(); // fail
});
引擎吸气剂:
get engine() {
return {
state: this.state,
register: target => {
this.setState(LazyloadUtils.registerOneTarget(target));
},
};
}
答案 0 :(得分:2)
理想情况下,您要检查setState方法正在更新的状态对象中的键
expect(wrapper.state('foo')).toEqual('bar')
如果您真的想监视方法本身,则可以在组件原型上模拟setState方法。在创建组件的浅表副本之前,您需要执行此操作。
it('shall update targets when engine register has been called', () =>
{
LazyloadProvider.prototype.setState = jest.fn();
const wrapper = shallow(
<LazyloadProvider>
<p>Wow</p>
</LazyloadProvider>
).instance();
expect(wrapper.setState).toHaveBeenCalled();
}
答案 1 :(得分:0)
如果您要在调用setState
之后继续测试,则应该监视而不是模拟该方法
it('shall update targets when engine register has been called', () =>
{
const setStateSpy = jest.spyOn(LazyloadProvider.prototype, 'setState');
const wrapper = shallow(
<LazyloadProvider>
<p>Wow</p>
</LazyloadProvider>
).instance();
expect(setStateSpy).toHaveBeenCalled();
// write more tests that want the dom to update
}