如何开玩笑地模拟 useHistory 钩子?

新手上路,请多包涵

我在带有打字稿的反应路由器 v5.1.2 中使用 UseHistory 钩子?运行单元测试时,我遇到了问题。

TypeError:无法读取未定义的属性“历史”。

 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() })); 但它仍然不起作用。

原文由 Ivan Martinyuk 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 745
2 个回答

在浅化使用 useHistory 的反应功能组件时,我需要相同的功能。

在我的测试文件中解决了以下模拟:

 jest.mock('react-router-dom', () => ({
  useHistory: () => ({
    push: jest.fn(),
  }),
}));

原文由 Proustibat 发布,翻译遵循 CC BY-SA 4.0 许可协议

这个对我有用:

 jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useHistory: () => ({
    push: jest.fn()
  })
}));

原文由 Erhan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进