简体   繁体   English

如何测试是否在componentDidMount中调用了方法?

[英]How to test if method was called inside componentDidMount?

I have following componentDidMount lifecycle: 我有以下componentDidMount生命周期:

componentDidMount () {
    window.scrollTo(0, 0);

    this.setState({
      loading: true,
    });

    if (token) return this.getUserData();
    return this.guestUserData();
  }

I want to test in jest/enzyme if componentDidMount ran and if guestUserData was called. 如果componentDidMount运行并且调用了guestUserData,我想在jest / enzyme中测试。

I wrote the following test: 我写了以下测试:

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();
  });

but I have error now: 但我现在有错误:

TypeError: Cannot set property guestUserData of #<Component> which has only a getter

Can somebody advice how to test if method was called in lifecycle and if lifecycle was called itself in one test if possible 有人可以建议如何测试方法是否在生命周期中调用,以及生命周期是否在一个测试中被调用(如果可能)

Just don't. 只是不要。 I believe getUserData is calling some external API(rather sending XHR or working with session storage or whatever). 我相信getUserData正在调用一些外部API(而不是发送XHR或使用会话存储或其他)。 So you just need to mock that external source and verify if it has been accessed right after component is created 因此,您只需要模拟该外部源并验证是否在创建组件后立即访问它

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();
});

This way you really test if 1. external API have been called on component init 2. API has been called with expected params 3. component knows what to do if API call fails 4. ... 这样你真的可以测试是否已经在组件init上调用了外部API 2.已经使用预期的参数调用了API 3.组件知道如果API调用失败该怎么办4. ...

In contrary checking if method this.getUserData has been called in cDM does not ensure any of items above. 在相反的检查,如果方法this.getUserData被称为清洁发展机制并不能保证任何物品之上。 What if this.getUserData itself does not call API? 如果this.getUserData本身不调用API怎么办? what if API failure is not handled properly there? 如果在那里没有正确处理API故障怎么办? We would still unsure on that. 我们仍然不确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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