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

时间:2019-05-03 15:05:47

标签: javascript reactjs jestjs enzyme

我有以下componentDidMount生命周期:

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

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

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

如果要运行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

有人可以建议如何测试方法是否在生命周期中被调用,以及是否可以在一个测试中调用生命周期本身

1 个答案:

答案 0 :(得分:2)

别这样。我相信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();
});

这样您就可以真正测试 1.组件初始化已调用外部API 2.已使用预期参数调用API 3.组件知道如果API调用失败该怎么办 4. ...

相反,检查cDM中是否已调用方法this.getUserData不能确保上面的任何项目。如果this.getUserData本身未调用API怎么办?如果API失败在那里无法正确处理怎么办?我们仍然不确定。