Búsqueda de sitios web

reactjs - No se puede probar la función envoltorio personalizada de react-router-dom v6 con Jest


Estoy tratando de escribir una función auxiliar que envuelva el componente MemoryRouter de React con el fin de facilitar la escritura de pruebas. Planeo escribir muchas pruebas para diferentes rutas, parámetros de URL, rutas que no coinciden, etc.

Sin embargo, nunca he hecho esto antes y he consultado la documentación de React Testing Library aquí e intenté seguir este video en YouTube. Además, leí este artículo en el blog del cual obtuve algunas ideas.

Me estoy acercando con esta función envolvente:

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 });
};

La prueba unitaria se ve así:

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');
  });
});

Sin embargo, tengo un 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.

Artículos relacionados