DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

7

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)