We're using Cypress for testing an app build with Create React App, and our CRA app is setting a custom import path in .env
– NODE_PATH=src/
– so that we can import files "absolutely", e.g. import Foo from 'components/Foo'
vs. import Foo from '../../components/Foo'
The problem is, if we import one of the files from our CRA into a Cypress test, and the imported file includes something like import routes from 'lib/routes'
Cypress doesn't know how to process that path and the import fails.
Let's say we have the following files:
/cypress/integration/test.js
import routes from '../../src/lib/routes';
// Tests here…
/src/lib/routes.js
import { routeHelpers } from 'lib/routes';
// Routing code here
In this scenario, when /cypress/integration/test.js
imports /src/lib/routes.js
it will encounter the absolute import of 'lib/routes'
and have no idea how to resolve that path.
Is there a way to set custom paths for Cypress to include when searching for imports in this way? In the case of this arbitrary example, it would mean telling Cypress to use src
as a directory to resolve imports from.
Easiest solution for this turned out to be simply running the cypress commands with NODE_PATH=src
. So my package.json
was simply updated to the following:
"scripts": {
"cypress:open": "NODE_PATH=src cypress open",
"cypress:run": "NODE_PATH=src cypress run",
},
I had a similar issue and I was using .env
with NODE_PATH=src
Solution: I removed .env
and created jsconfig.json
for absolute imports.
{
"compilerOptions": {
"baseUrl": "src"
},
"include": ["src"]
}
This is the recommended approach in the CRA docs: https://create-react-app.dev/docs/importing-a-component/#absolute-imports
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