如何嘲笑useHistory挂钩中的玩笑

如何嘲笑useHistory挂钩中的玩笑

本文介绍了如何嘲笑useHistory挂钩中的玩笑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有脚本的React Router v5.1.2使用UseHistory挂钩吗?在运行单元测试时,我遇到了问题。

I am using UseHistory hook in react router v5.1.2 with typescript? When running unit test, I have got issue.



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

Also i have tried use jest.mock('react-router', () =>({ useHistory: jest.fn() })); but it still does not work.

推荐答案

在浅化使用 useHistory 的React功能组件时,我需要相同的内容。

I needed the same when shallowing a react functional component that uses useHistory.

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

Solved with the following mock in my test file:

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

这篇关于如何嘲笑useHistory挂钩中的玩笑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:14