Jest + Typescript + Absolute paths (baseUrl) gives error: Cannot find module
I was struggling with the same problem and actually it turns out that a simple change seems to do the trick.
I just updated the moduleDirectories
field in jest.config.js
.
Before
moduleDirectories: ['node_modules']
After
moduleDirectories: ['node_modules', 'src']
Hope it helps.
As many here pointed out moduleNameMapper
in jest.config.js
needs to define paths specified in tsconfig.json
. For example, if you have paths in tsconfig.json
defined as follows
// tsconfig.json{ ... "baseUrl": "src", "paths": { "@alias/*": [ 'path/to/alias/*' ] } ...}
then your jest.config.js
needs to provide those paths in moduleNameMapper
in the following format:
// jest.config.jsmodule.exports = { 'roots': [ '<rootDir>/src' ], 'transform': { '^.+\\.tsx?$': 'ts-jest' }, 'moduleNameMapper': { '@alias/(.*)': '<rootDir>/src/path/to/alias/$1' }};
Having that we can improve our jest.config.js
to convert paths defined in tsconfig.json
automatically. Here is a Gist code snippet for that:
// jest.config.jsfunction makeModuleNameMapper(srcPath, tsconfigPath) { // Get paths from tsconfig const {paths} = require(tsconfigPath).compilerOptions; const aliases = {}; // Iterate over paths and convert them into moduleNameMapper format Object.keys(paths).forEach((item) => { const key = item.replace('/*', '/(.*)'); const path = paths[item][0].replace('/*', '/$1'); aliases[key] = srcPath + '/' + path; }); return aliases;}const TS_CONFIG_PATH = './tsconfig.json';const SRC_PATH = '<rootDir>/src';module.exports = { 'roots': [ SRC_PATH ], 'transform': { '^.+\\.tsx?$': 'ts-jest' }, 'moduleNameMapper': makeModuleNameMapper(SRC_PATH, TS_CONFIG_PATH)};
Here is how I got moduleNameMapper working.
With the below config in my tsconfig:
"paths": { "@App/*": [ "src/*" ], "@Shared/*": [ "src/Shared/*" ] },
Here's the moduleNameMapper:
"moduleNameMapper": { "@App/(.*)": "<rootDir>/src/$1", "@Shared/(.*)": "<rootDir>/src/Shared/$1"}