12
votes

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.

Example

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.

2
Cypress tests are generally decoupled from the app, i.e you test the live DOM. Not sure about React, but in Vue and Angular webpack bundles imports so at runtime you are either importing a bundle or the whole app is one bundle. You could still use lib/routes in a test e.g to provide fixture strings, but you will either need to copy the file to Cypress' fixture folder or adjust the relative path from Cypress integration folder to your source lib folder. - user8745435
@eric99 Clarified the original question with an example. The issue is that when Cypress encounters any absolute import paths inside of files that it imports, it doesn't know how to resolve them. Copying to Cypress' fixture folder wouldn't solve that path resolution issue, nor would using any relative path from the Cypress test. - cmal

2 Answers

12
votes

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",
},
0
votes

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