Joseph Freeman
Joseph Freeman

Reputation: 1784

React Jest/Enzyme Testing: useHistory Hook Breaks Test

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.

Upvotes: 2

Views: 846

Answers (1)

Joseph Freeman
Joseph Freeman

Reputation: 1784

So I figured it out. I was on the right path by creating a mock for the useHistory() hook, I just defined it in the wrong place. Turns out 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.

Upvotes: 4

Related Questions