繁体   English   中英

如何测试是否在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM