I am using UseHistory hook in react router v5.1.2 with typescript? When running unit test, I have got issue.
TypeError: Cannot read property \'history
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 (
<>
history.push('/whatever')}>Click me
...
>
)
});
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(
,
).find('.selector').at(1);
const { onClick } = wrapper.props();
act(() => {
onClick();
});
expect(historyMock.push.mock.calls[0][0]).toEqual('/whatever');
});