React Jest/Enzyme Testing: useHistory Hook Breaks Test

烂漫一生 提交于 2021-02-10 17:45:48

问题


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`

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

UPDATE:

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.


回答1:


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.



来源:https://stackoverflow.com/questions/60404319/react-jest-enzyme-testing-usehistory-hook-breaks-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!