How to mock a React component lifecycle method with Jest and Enzyme?

别说谁变了你拦得住时间么 提交于 2019-12-03 03:22:01
Andreas Köberle

This will not work with jest this way as jest.fn only have a parameter for the implementation. But more important, you should not spy on the internals of the object you want to test. You should think of Foo as a black box where you can put some properties in and get some stuff rendered back. Then you realize that there is no need to test that internal functions of Foo, like componentDidMount, get called. The only thing that matters is the output of the black box.

But if you really want do test it anyway:

const spy = jest.fn()
const componentDidMount = Foo.prototype.componentDidMount
Foo.prototype.componentDidMount = function(){
  spy()
  componentDidMount()
}

As of Jest 19, you can do this:

describe('<App />', () => {
  it('calls componentDidMount', () => {
    const spy = jest.spyOn(App.prototype, 'componentDidMount');
    const wrapper = mount(<App />);
    expect(spy).toHaveBeenCalled();
    spy.mockReset();
    spy.mockRestore();
  });
});

jest.spyOn returns a mock function with all the normally available methods such as mockClear, mockReset and mockRestore.

Make sure to set up your spy before you mount with enzyme or create with react-test-renderer so that the created instance has a reference to the mocked function being spied on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!