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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…