![](/img/trans.png)
[英]How to test a component function being called when componentDidMount?
[英]How to test if method was called inside componentDidMount?
我有以下componentDidMount生命周期:
componentDidMount () {
window.scrollTo(0, 0);
this.setState({
loading: true,
});
if (token) return this.getUserData();
return this.guestUserData();
}
如果componentDidMount运行并且调用了guestUserData,我想在jest / enzyme中测试。
我写了以下测试:
test("should call method in componentDidMount", () => {
Component.prototype.guestUserData = jest.fn();
const spy = jest.spyOn(Component.prototype, 'guestUserData');
const wrapper = shallow(<Component {...defaultProps} />);
expect(spy).toHaveBeenCalled();
});
但我现在有错误:
TypeError: Cannot set property guestUserData of #<Component> which has only a getter
有人可以建议如何测试方法是否在生命周期中调用,以及生命周期是否在一个测试中被调用(如果可能)
只是不要。 我相信getUserData
正在调用一些外部API(而不是发送XHR或使用会话存储或其他)。 因此,您只需要模拟该外部源并验证是否在创建组件后立即访问它
const fetchUserData = jest.fn();
jest.mock('../api/someApi', () => ({
fetchUserData,
}));
beforeEach(() => {
fetchUserData.mockClear();
});
it('calls API on init', () => {
shallow(<Yourcomp {...propsItNeeds} />);
expect(fetchUserData).toHaveBeenCalledWith(paramsYouExpect);
});
it('does something if API call fails', () => {
fetchUserData.mockRejectedValue();
const wrapper = shallow(<Yourcomp {...propsItNeeds} />);
expect(wrapper.find(ErrorMessage).props().children).toEqual('Failed to load. Try again');
// or even
expect(wrapper).toMatchSnapshot();
});
这样你真的可以测试是否已经在组件init上调用了外部API 2.已经使用预期的参数调用了API 3.组件知道如果API调用失败该怎么办4. ...
在相反的检查,如果方法this.getUserData
被称为清洁发展机制并不能保证任何物品之上。 如果this.getUserData
本身不调用API怎么办? 如果在那里没有正确处理API故障怎么办? 我们仍然不确定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.