DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

Testing useNavigate

This will be a short post where i will show you how to test useNavigate the right way when used in a react component.

First we will mock the react-router-dom, and then inside the mock, we will define useNavigate with the 'mockedUsedNavigate' variable.

const mockedUsedNavigate = jest.fn();
jest.mock('react-router-dom', () => ({
    ...(jest.requireActual('react-router-dom')),
    useNavigate: () => mockedUsedNavigate,
}))
Enter fullscreen mode Exit fullscreen mode

After mocking it we will describe the test and actually doing the testing

We will render the component which in this case is 'Test', afet this we will call the divElement and afterwards we will fire an event simulating an onClick event to the divElement.
Finally we will check if mockedUsedNavigate is actually being called.

describe('Test component', () => {

    it('should render the navigate of it', () => {

        const setUp = () => {
            const {getAllByTestId} = render(
                    <Test/>
            )
            const divElement = getAllByTestId('navigateCart')[0];
            return {
                divElement,
            }
        }

        const {divElement} = setUp();
        fireEvent.click(divElement)
        expect(mockedUsedNavigate).toBeCalled()
        mockedUsedNavigate.mockRestore();
Enter fullscreen mode Exit fullscreen mode

Hope someone found it useFul.

Lautaro

Top comments (0)