Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set custom default import paths for Cypress

Tags:

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.

like image 602
cmal Avatar asked Dec 19 '18 19:12

cmal


2 Answers

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",
},
like image 182
cmal Avatar answered Oct 27 '22 12:10

cmal


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

like image 1
wdm Avatar answered Oct 27 '22 10:10

wdm