Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolve file paths in Jest

Tags:

webpack

jestjs

I have a React based app in which I have a test file which I intend to run through Jest. The test requires importing classes from other files. The file that I import further imports other files and so on. The project has alias for many paths to lessen the typing when importing them (this is configured in Webpack).

When I run jest command in npm, I get an error saying 'Cannot find module ...`. How can I resolve file paths when running Jest? I can't mock the modules as these are custom modules which are required to run the test.

like image 378
darKnight Avatar asked Apr 02 '18 18:04

darKnight


People also ask

What is transformIgnorePatterns?

json file. transformIgnorePatterns option can be used to specify which files shall be transformed by Babel. Many react-native npm modules unfortunately don't pre-compile their source code before publishing. I have react-navigation package installed in my app so I added this regex value in transformIgnorePatterns.

What is preset in jest?

preset [string] Default: undefined. A preset that is used as a base for Jest's configuration. A preset should point to an npm module that exports a jest-preset. json module on its top level.


1 Answers

You could add 1 line to your Jest config file like this:

module.exports = {
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1"
  }
}

The configuration line above uses regex to map imports starting with the @ character.

Note: (this above configuration code is assuming your source code is located in "project_root/src/"

Then, your import statements in your jest tests will look like this:

import {RepositoryController} from '@/controller/repository'

Which maps to project_root/src/controller/repository. This is much better then the relative path: ../../../src/controller/repository my project would regularly require.

like image 176
levibostian Avatar answered Sep 24 '22 18:09

levibostian