'[TypeError: (0 , react_router_dom_1.useParams) is not a function]

I have a component which uses react-router-dom's useParams hook to get params.

It is used in my component as :

/// Child.tsx

const Child = () => {
    const {id} = useParams();
    return <div>Child!</div>
}

while writing unit tests, i'm facing the above error while mounting the component.

Things I tried is mocking useParams like this :

jest.mock('react-router-dom', () => ({         /// This is at top level after imports
  ...jest.requireActual('react-router-dom'),
  useParams: () => ({
    id: 'txnabcd',
  }),
}))

Unit test:

descibe("mounts", ()=>{
      it("mounts the component", ()=>{
         mount(<Child />       /// Failing here 
       })
  })

Where could I be possibly wrong?



Solution 1:[1]

I ended up mocking react-router-dom's useParams

// __ mocks __/react-router-dom.js

const reactRouter = require('react-router-dom')
const useParams = jest.fn()
module.exports = {
  ...reactRouter,
  useParams,
}

Inside test-file standard import and mockReturnvalue for useParams:

import { useParams } from 'react-router-dom'
...
useParams.mockReturnValue({ id: 'txnabcd' })

Solution 2:[2]

Instead of mocking 3rd-party code you might try rendering the Child component into a routing context and route with an id route param.

Example:

import { MemoryRouter as Router, Routes, Route } from 'react-router-dom';

describe("mounts", () => {
  it("mounts the component", () => {
    mount(
      <Router initialEntries={["/test/1234"]}>
        <Routes>
          <Route path="/test/:id" element={<Child />} />
        </Routes>
      </Router>
    ); 
  });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Simmi George
Solution 2 Drew Reese