How to unit test a react event handler that contains history.push using Jest and Enzyme?

十年热恋 提交于 2019-11-30 12:41:55

It's actually simple, you can pass in any props to the component when shallow rendering it inside the test, like that:
const wrapper = shallow(<SearchForm history={historyMock} />)

By the way, inside onSubmit, you should call like this.props.history.push(...).

Now, to create a mock (more info in the documentation), you can write like this in the test:
const historyMock = { push: jest.fn() };

Keep in mind that you are actually mocking only the push method of the history object, if you use more methods inside the component and want to test them, you should create a mock to each one tested.

And then, you need to assert that the push mock was called correctly. To do that, you write the assertion necessary:
expect(historyMock.push.mock.calls[0]).toEqual([ (url string), (state object) ]);
Use the needed (url string) and (state object) to be asserted.

mock it!

if you create a folder __mocks__ and add the module history to it, you can override it´s functionality and check if it was called.

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