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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With