React Jest /酶测试:useHistory Hook Breaks测试

时间:2020-02-25 22:48:54

标签: reactjs react-router jestjs enzyme

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

const Login: FunctionComponent = () => {

    const history = useHistory();

    //extra logic that probably not necessary at the moment

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

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

TypeError: Cannot read property 'history' of undefined`

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

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

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

更新:

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

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

在进行上述测试时,不会导致历史记录不确定。

1 个答案:

答案 0 :(得分:0)

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

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

通过以上操作,测试将在未定义历史记录的情况下运行。

相关问题