Can't test react-router-dom v6 custom wrapper function with Jest

Viewed 148

I am trying to write a helper function that wraps React's MemoryRouter component in order to make writing tests easier. I'm planning to be writing a lot of tests for different routes, URL params, non matching routes, etc.

However, I have never done this before and I've referenced documentation from React Testing Library here and tried to follow along with this video on YouTube. Also, read this blog post which I got some ideas from.

I'm getting close with this wrapper function:

import { render } from '@testing-library/react';
import { FC, ReactElement } from 'react';
import { MemoryRouter, MemoryRouterProps, Routes } from 'react-router-dom';

const AllTheProviders: FC<{ children: React.ReactNode }> = ({ children }) => {
  return (
    <MemoryRouter>
      <Routes>{children}</Routes>
    </MemoryRouter>
  );
};

export const renderWithRouter = (ui: ReactElement, options?: MemoryRouterProps) => {
  render(ui, { wrapper: AllTheProviders, ...options });
};

The unit test looks like this:

import { Route } from 'react-router-dom';
import { Profile } from './profile';
import { renderWithRouter } from './test-utils';

const mockUseParams = jest.fn();

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useParams: () => mockUseParams,
}));

describe('Profile', () => {
  it('should fetch the username from the given url param', () => {
    renderWithRouter(
      <Route path="/profile/:username" element={<Profile />} />,
      { initialEntries: ['/profile/test'] }
    );
    expect(mockUseParams).toHaveBeenCalledWith('test');
  });
});

However, I have an error:

  expect(jest.fn()).toHaveBeenCalledWith(...expected)

    Expected: "test"

    Number of calls: 0

      16 |       { initialEntries: ['/profile/test'] }
      17 |     );
    > 18 |     expect(mockUseParams).toHaveBeenCalledWith('test');
         |                           ^
      19 |   });
      20 | });
      21 |

      at Object.toHaveBeenCalledWith (src/app/pages/profile.spec.tsx:18:27)

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 2 passed, 3 total
Snapshots:   0 total
Time:        1.39 s
Ran all test suites related to changed files.

Watch Usage: Press w to show more.
0 Answers
Related