I'm making a unit test in a React application (that i created with the command "create-react-app" without using any framework or build tool), that i am developing for a university project, using Jest and React Testing Library. One of the modules that i'm importing in the test file is the one below
import { BrowserRouter } from "react-router-dom";
I have this dependency installed in my package.json file, but i keep receiving the message below every time i try to start the test
Test suite failed to run
Cannot find module 'react-router-dom' from 'src/App.test.js'
1 | import React from "react";
2 | import { render, screen } from "@testing-library/react";
> 3 | import { BrowserRouter } from "react-router-dom";
| ^
4 | import App from "./App";
I've tried to reinstall my dependencies, but it didn't work. Here is my package.json file:
{
"name": "apoiaacao",
"version": "0.1.0",
"private": true,
"dependencies": {
"axios": "^1.7.9",
"bootstrap": "^5.3.3",
"cra-template": "1.2.0",
"react": "^18.2.0",
"react-confirm-alert": "^3.0.6",
"react-dom": "^18.2.0",
"react-router-dom": "^7.1.5",
"react-scripts": "^5.0.1",
"react-toastify": "^11.0.3",
"web-vitals": "^4.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
"eslint": "^8.57.1",
"eslint-config-prettier": "^10.0.2",
"jest": "^27.5.1",
"prettier": "3.5.2",
"prettier-eslint": "^16.3.0"
}
}
I don't know why i can't run the test properly. I've seen some posts with problems similar to mine, but none of the solutions in the comments of those posts solved my problem. Maybe the only solution is to do a transition of my project to a Vite + React application.
As of react-router v7, you need to change your import to from "react-router"
import { BrowserRouter } from "react-router";
Also you can change packages.json to install "react-router" instead of "react-router-dom":
"dependencies": {
...
"react-dom": "^18.2.0",
"react-router": "^7.1.5", // No longer react-router-dom
}
Heads up that after you get that working, there's a fair chance you might then encounter this "TextEncoder not defined"…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With