Mocking useParams from react-router-dom in Vitest returns {} instead of actual mock

492 Views Asked by At

I'm working on a React project where I'm using react-router-dom. For testing purposes I'm using Vitest to mock the useParams hook. However, after mocking useParams and adding a console log to check the mock, I'm only getting {} instead of the actual mock value.

Here's a simplified version of what my code and test look like:

Code (Component.js):

import React from 'react';
import { useParams } from 'react-router-dom';

const MyComponent = () => {
  const params = useParams();
  
  console.log('useParams:', params); // For debugging

  return (
    <div>
      {/* Some JSX code using `id` */}
    </div>
  );
};

export default MyComponent;

Test (Component.test.js):

import { render } from '@testing-library/react';
import { describe, it, vi } from 'vitest';
import { useParams } from 'react-router-dom';
import MyComponent from './Component';

vi.mock('react-router-dom', () => ({
  ...vi.importActual('react-router-dom'),
  useParams: vi.fn().mockReturnValue({ id: '123' }),
}));

describe('MyComponent', () => {
  it('should use mocked useParams', () => {
    render(<MyComponent />);
    // Expectations or assertions
  });
});

When running the test, the console log inside MyComponent outputs {} instead of the mocked { id: '123' }. I'm not sure what I'm missing or doing incorrectly.

Has anyone encountered a similar issue or knows how to correctly mock useParams using Vitest in this context?

1

There are 1 best solutions below

0
On

Instead of trying to mock code you should probably just provide a router/routing context and a route with the params you'd like to "mock" for the test.

Example:

import { render } from '@testing-library/react';
import { describe, it, vi } from 'vitest';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import MyComponent from './Component';

describe('MyComponent', () => {
  it('should access route with "id" param', () => {
    render(
      <MemoryRouter initialEntries={["/test/123"]}>
        <Routes>
          <Route path="/test/:id" element={<MyComponent />} />
        </Routes>
      </MemoryRouter>
    );
    // Expectations or assertions
  });
});