【问题标题】:jest enzyme test method in componentDidMountcomponentDidMount 中的笑话酶测试方法
【发布时间】:2018-06-21 04:48:57
【问题描述】:

我正在尝试测试是否在 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() 是否被调用?

谢谢!

【问题讨论】:

    标签: reactjs enzyme jestjs


    【解决方案1】:

    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,shallow 比 rest 两个更快,因此它减少了运行测试套件所需的时间。

    【讨论】:

      【解决方案2】:

      您可以像使用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();
      });
      

      【讨论】:

      • 你最后的模拟清关调用(mockClear())是没用的,因为失败的expect会立即返回函数。这些调用应该与测试分开,在拆解部分的某个地方。
      猜你喜欢
      • 1970-01-01
      • 2019-04-05
      • 2017-08-18
      • 1970-01-01
      • 2020-06-19
      • 2021-09-07
      • 2018-03-23
      • 2020-06-14
      • 1970-01-01
      相关资源
      最近更新 更多