Jest testing with absolute import of create-react-app

Absolute Imports

By default ES6 modules in create-react-app use relative paths to import files. This introduces ugly importing statements for nested files.

import Button from '../../../Elements/Button';
import Header from '../../../Partials/Header';

Instead, we can use Absolute Imports to shorten the imported file path. Basically, use some particular path as the root, all importing will be relatively located based on this root. For example, if the root path is /home/joy/Projects/hello/src, and suppose all your source files are located in this folder, the statements above could be replaced with:

import Button from 'Elements/Button';
import Header from 'Partials/Header';

For a create-react-app application, this is easy:

  1. Create a .env file at the root level (same level as package.json)
  2. Set an environment variable, NODE_PATH to src/: NODE_PATH=src/.

That's it.

Testing

So far, this works well and saves a lot of unnecessary ../ in our files. However, when you start to write unit testing code in Jest. You will get error messages when running yarn test (react-scripts-ts test --env=jsdom):

 FAIL  src/__tests__/pages/NotFound.test.tsx
  ● Test suite failed to run

    Cannot find module 'src/components/Message' from 'NotFound.tsx'
      
      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:179:17)
      at Object.<anonymous> (src/pages/NotFound.tsx:7:16)

Some articles (Support for imports with absolute path #64, Jest gives Cannot find module when importing components with absolute paths) suggest adding moduleDirecties in jest section of package.json:

"jest": {
    "moduleDirectories": ["node_modules", "src"],
    ...
}

However, for create-react-app, it show errors:

Selection 059

After googling and trying a lot, this way works:

Modify the yarn test command in package.json file to append --modulePaths=src: react-scripts-ts test --env=jsdom --modulePaths=.. Where the value of modulePaths is your root path. . means the location where package.json is.

Enjoy it.

References: