componentDidMount中的jest酶测试方法

时间:2018-01-11 19:01:31

标签: reactjs enzyme jest

我正在尝试测试在componentDidMount中调用的方法:

private timerToken;

public componentDidMount() {
    this.timerToken = setInterval(() => { this._getWebJobStatus(); }, 2000);
}

test("_getWebJobStatus() is called", () => {
        const spy = jest.spyOn(UploadStatus.prototype, "componentDidMount").mockReturnThis();
        const wrapper = mount(<testComponent />);
        const component = wrapper.instance() as testComponent;
        const _getWebJobStatusMock = jest.fn();
        component['timerToken'] = _getWebJobStatusMock;
        expect(spy).toHaveBeenCalledTimes(1);   // this works
        expect(_getWebJobStatusMock).toHaveBeenCalled();   //this is not working
    });

如何测试_getWebJobStatus()?

谢谢!

2 个答案:

答案 0 :(得分:2)

Jest非常支持测试Timer功能。您可以按照以下方式测试代码:

jest.useFakeTimers();

describe("Component", () => {
    const getComponent = () => shallow(<Component />);

    it('should call setInterval on mounting', () => {
        const component = getComponent();

        expect(setInterval).toHaveBeenCalledWith(expect.any(Function), 1000);
    });
});

有关此问题的文档可在此处找到:https://facebook.github.io/jest/docs/en/timer-mocks.html
附:尽可能避免使用酶提供的mount或render,浅比rest rest快,因此它减少了运行测试套件所需的时间。

答案 1 :(得分:0)

您可以使用与componentDidMount相同的方式执行此操作。像这样:

test('_getWebJobStatus() is called', () => {  
  const componentDidMountSpy = jest.spyOn(UploadStatus.prototype, 'componentDidMount');
  const componentGetWebJobStatusMock = jest.spyOn(UploadStatus.prototype, '_getWebJobStatus');

  const wrapper = Enzyme.shallow(<UploadStatus/>);

  expect(UploadStatus.prototype.componentDidMount).toHaveBeenCalledTimes(1);
  expect(UploadStatus.prototype._getWebJobStatus).toHaveBeenCalledTimes(1);

  componentDidMountSpy.mockClear();
  componentGetWebJobStatusMock.mockClear();
});