我有以下componentDidMount生命周期:
componentDidMount () {
window.scrollTo(0, 0);
this.setState({
loading: true,
});
if (token) return this.getUserData();
return this.guestUserData();
}我想在jest/酶中测试componentDidMount是否运行,guestUserData是否被调用。
我写了以下测试:
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如果可能的话,有人可以建议如何测试方法是否在生命周期中调用,以及生命周期本身是否在一次测试中调用
发布于 2019-05-04 05:52:55
我相信getUserData正在调用一些外部应用程序接口(而不是发送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();
});这样你就可以真正地测试是否1.外部API已经在组件init上被调用了2. API已经被调用了预期的参数3.组件知道如果API调用失败该怎么做4 . .
相反,检查cDM中是否调用了this.getUserData方法并不能确保上面的任何一项。如果this.getUserData本身不调用API怎么办?如果API故障在那里没有得到正确的处理,该怎么办?我们仍然不能确定这一点。
https://stackoverflow.com/questions/55972552
复制相似问题