Petrando Richard
Petrando Richard

Reputation: 21

cannot detect installed react-router-dom package when running unit tests

I want to learn react testing library with react-router-dom. I created the app using npx create-react-app command. The resulting code already has an App.test.js in the parent folder:

import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
  render(<App />);
  const linkElement = screen.getByText(/learn react/i);
  expect(linkElement).toBeInTheDocument();
});

When I run npm test, it passes successfully as expected. I installed React-Router-DOM with npm i react-router-dom and I wrapped the main App.js with the BrowserRouter component.

import { BrowserRouter } from 'react-router-dom'
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <BrowserRouter>
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    </BrowserRouter>
  );
}

export default App;

But now the test failed with the following error:

Cannot find module 'react-router-dom' from 'src/App.js'

screenshot of the failed test message

Why the unit test cannot detect react-router-dom, which has already properly installed?

Github repo of my code so far.

Note: I have already tested wrapped my component using MemoryRouter instead of BrowserRouter, but still the same error.

Upvotes: 1

Views: 723

Answers (2)

ivanlp4
ivanlp4

Reputation: 1

I had the same problem and, as one commentator said, I downgraded react router to v6 with npm i react-router-dom@6. It helped me.

Upvotes: -1

Mannkumar Pandya
Mannkumar Pandya

Reputation: 25

Everything seems fine, just update the BrowseRouter import from this in App.js:

import { BrowserRouter } from 'react-router-dom'

to this:

import { BrowserRouter } from 'react-router';

-> Please make sure you have these 3 packages installed:

  • react-dom
  • react-router
  • react-router-dom

Hope this helps..

reference: https://www.npmjs.com/package/react-router-dom

Upvotes: -1

Related Questions