如何嘲笑useHistory挂钩中的玩笑?
我在带有打字稿的React Router v5.1.2中使用UseHistory挂钩吗?运行单元测试时,我遇到了问题。
TypeError:无法读取未定义的属性“ history”。
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();
    });
});
我也尝试使用,jest.mock('react-router', () =>({ useHistory: jest.fn()
}));但仍然无法正常工作。
回答:
浅化使用的反应功能组件时,我需要相同的内容useHistory。
在我的测试文件中解决了以下模拟问题:
jest.mock('react-router-dom', () => ({  useHistory: () => ({
    push: jest.fn(),
  }),
}));
以上是 如何嘲笑useHistory挂钩中的玩笑? 的全部内容, 来源链接: utcz.com/qa/426034.html








