如何嘲笑useHistory挂钩中的玩笑? [英] How to mock useHistory hook in jest?

查看:750
本文介绍了如何嘲笑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.


TypeError:无法读取未定义的属性 history。

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();
    });
});

我也尝试使用 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挂钩中的玩笑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆