Babel Module Resolver with Jest

 by Robin Wieruch
 - Edit this Post

This tutorial is part 2 of 2 in the series.

Here you will learn how to use Jest with Babel Module Resolver for aliases that are defined in your .babelrc file:

{
...
"plugins": [
[
"module-resolver",
{
"root": ["./"],
"alias": {
"@components": "./src/components",
"@constants": "./src/constants",
}
}
],
]
}

In order to get the same alias mappings to Jest, the jest.config.js file needs to look like this:

module.exports = {
roots: ['<rootDir>'],
moduleFileExtensions: ['js', 'ts', 'tsx', 'json'],
testPathIgnorePatterns: ['./node_modules/'],
moduleNameMapper: {
'^@components(.*)$': '<rootDir>/src/components$1',
'^@constants(.*)$': '<rootDir>/src/constants$1',
},
testEnvironment: 'jsdom',
transform: {
'^.+\\.(js|jsx|ts|tsx)$': 'babel-jest',
},
};

Now you can use import statemes with aliases in your Jest testing environment too.

Keep reading about 

In this brief walkthrough, we will use Babel Module Resolver to convert relative paths to aliases for your entire JavaScript application. You can install it via the command line: And use it in your…

Here you will learn how to use TypeScript with Babel Module Resolver for aliases that are defined in your .babelrc file: In order to get the same alias mappings to TypeScript, the tsconfig.json file…

The Road to React

Learn React by building real world applications. No setup configuration. No tooling. Plain React in 200+ pages of learning material. Learn React like 50.000+ readers.

Get it on Amazon.