Finglish
Finglish

Reputation: 9986

Why does jest testing break when adding react-router-dom to a react app with create-react-app

I am running a create-react-app with react-16.8.6, and no modifications except for adding react-router to the mix. Now tests don't work.

After rolling things back, I found that the base test fails as soon as I import ANY part of the "react-router-dom" library. Any ideas whats going wrong?

Below is the App.js and App.test.js when I comment out the line:

import { Switch } from "react-router-dom";

the tests run without issue. When I return the line to the code I get the following error:

Test suite failed to run

Cannot find module 'react' from 'react-router-dom.js'

However, Jest was able to find:

'./App.css'
'./App.js'
'./App.test.js'

App.js

import React from "react";
import { Switch } from "react-router-dom";
import logo from "./logo.svg";
import "./App.css";

function App() {
  return (
    <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>
  );
}

export default App;

app.test.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

it("renders without crashing", () => {
  const div = document.createElement("div");
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});

Upvotes: 2

Views: 2628

Answers (2)

Camilla
Camilla

Reputation: 61

Ran into the same issue, and was thinking I could elaborate on the solution for people who run into the same.

It is not resolved by deleting node_modules and yarn.lock/package-lock.json. Instead, as @Finglish mentions in their comment above, you probably have missing dependencies.

To fix the missing deps:

  1. Get the depcheck package.
  2. Run it in your project folder to see which dependencies you're missing.
  3. Install the missing dependencies.
  4. Run tests again to make sure everything is working.

Upvotes: 0

Skyrocker
Skyrocker

Reputation: 1049

That might be some package manager installation issues. Try to do a fresh install:

rm -rf ./node_modules && rm yarn.lock && yarn

or in case if you're using npm:

rm -rf ./node_modules && rm package-json.lock && npm install

BTW, what is the version of the react-router-dom that you're installing? I've just tried it on the new create-react-app project, installed the latest version of router, but can't reproduce this error (enter image description here)

Upvotes: 2

Related Questions