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' of undefined.
import { mount } from 'enzyme';
import React from 'react';
import {Action} from 'history';
import * as router from 'react-router';
import { QuestionContainer } from './QuestionsContainer';
describe('My questions container', () => {
beforeEach(() => {
const historyHistory= {
replace: jest.fn(),
length: 0,
location: {
pathname: '',
search: '',
state: '',
hash: ''
},
action: 'REPLACE' as Action,
push: jest.fn(),
go: jest.fn(),
goBack: jest.fn(),
goForward: jest.fn(),
block: jest.fn(),
listen: jest.fn(),
createHref: jest.fn()
};//fake object
jest.spyOn(router, 'useHistory').mockImplementation(() =>historyHistory);// try to mock hook
});
test('should match with snapshot', () => {
const tree = mount(<QuestionContainer />);
expect(tree).toMatchSnapshot();
});
});
Also i have tried use jest.mock('react-router', () =>({ useHistory: jest.fn() }));
but it still does not work.
I needed the same when shallowing a react functional component that uses
useHistory
.Solved with the following mock in my test file:
This one worked for me:
Here's a more verbose example, taken from working test code (since I had difficulty implementing the code above):
Component.js
Component.test.js
In github react-router repo i found that useHistory hook uses singleton context, when i started use in mount MemoryRouter it found context and started works. So fix it