cmal
cmal

Reputation: 1791

Set custom default import paths for Cypress

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.

Upvotes: 14

Views: 7142

Answers (2)

wdm
wdm

Reputation: 7189

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

Upvotes: 1

cmal
cmal

Reputation: 1791

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

Upvotes: 12

Related Questions