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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay