React Jest/Enzyme测试:useHistory Hook Breaks测试 [英] React Jest/Enzyme Testing: useHistory Hook Breaks Test

查看:183
本文介绍了React Jest/Enzyme测试:useHistory Hook Breaks测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对React还是很陌生,所以请原谅我的无知.我有一个组件:

I'm fairly new to React, so please forgive my ignorance. I have a component:

const Login: FunctionComponent = () => {

    const history = useHistory();

    //extra logic that probably not necessary at the moment

    return (
        <div>
            <form action="">
                ...form stuff
            </form>
        </div>
    )
}

当尝试编写笑话/酶测试时,我编写的一个测试用例由于以下错误而失败 `›遇到声明异常

When attempting to write jest/enzyme test, the one test case I've written is failing with the following error ` › encountered a declaration exception

TypeError: Cannot read property 'history' of undefined`

我试图用玩笑来模拟useHistory,就像这样:

I've tried to use jest to mock useHistory like so:

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

但是它什么都不做:(我也遇到同样的错误.我们将不胜感激

but this does nothing :( and I get the same error. Any help would be most appreciated

更新:

所以我想通了.我在正确的路径上为错误定义的useHistory()钩子创建了模拟.将模拟需要定义在测试方法范围之外(至少对于useHistory),例如:

So I figured it out. I was on the right path creating a mock for the useHistory() hook, I defined in the wrong place. Turns the mock needs to be define (at least for useHistory) outside of the scope of the test methods, ex:

import { shallow } from 'enzyme';
import React from 'react';
import Login from './app/componets/login.component';

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

/**
 * Test suite describing Login test
describe('<LoginPage>', () => {
    test('should test something', () => {
         //expect things to happen
    });
})

在进行上述测试时,不会导致历史记录未定义失败.

With the above test runs without failing on history being undefined.

推荐答案

所以我知道了.我在正确的路径上为useHistory()钩子创建了一个模拟,但在错误的位置定义了该模拟.使得需要在测试方法范围之外定义(至少对于useHistory)模拟,例如:

So I figured it out. I was on the right path creating a mock for the useHistory() hook, I defined in the wrong place. Turns the mock needs to be define (at least for useHistory) outside of the scope of the test methods, ex:

import { shallow } from 'enzyme';
import React from 'react';
import Login from './app/componets/login.component';

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

/**
 * Test suite describing Login test
describe('<LoginPage>', () => {
    test('should test something', () => {
         //expect things to happen
    });
})

使用上述方法,可以在未定义历史记录的情况下运行测试.

With the above, the test runs without failing on history being undefined.

这篇关于React Jest/Enzyme测试:useHistory Hook Breaks测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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