How to mock useHistory hook in jest?
Solution 1:
I needed the same when shallowing a react functional component that uses useHistory
.
Solved with the following mock in my test file:
jest.mock('react-router-dom', () => ({
useHistory: () => ({
push: jest.fn(),
}),
}));
Solution 2:
This one worked for me:
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: jest.fn()
})
}));
Solution 3:
Here's a more verbose example, taken from working test code (since I had difficulty implementing the code above):
Component.js
import { useHistory } from 'react-router-dom';
...
const Component = () => {
...
const history = useHistory();
...
return (
<>
<a className="selector" onClick={() => history.push('/whatever')}>Click me</a>
...
</>
)
});
Component.test.js
import { Router } from 'react-router-dom';
import { act } from '@testing-library/react-hooks';
import { mount } from 'enzyme';
import Component from './Component';
it('...', () => {
const historyMock = { push: jest.fn(), location: {}, listen: jest.fn() };
...
const wrapper = mount(
<Router history={historyMock}>
<Component isLoading={false} />
</Router>,
).find('.selector').at(1);
const { onClick } = wrapper.props();
act(() => {
onClick();
});
expect(historyMock.push.mock.calls[0][0]).toEqual('/whatever');
});