'Typescript paths not resolving when running jest?
Attempting to convert this project over to jest using these instructions. I have everything working except for the files that use the paths
configuration:
"paths": {
"@fs/*": ["./src/*"],
"@test/*": ["./test/*"]
}
It looks as if when the tests are run the import statements do not resolve and this is logged:
Cannot find module '@fs/container/validation/ValidationContext' from 'Core.spec.ts'
1 | import { ValidationOptions } from "@fs/container/validation/ValidationOptions";
> 2 | import { ValidationContext } from "@fs/container/validation/ValidationContext";
| ^
3 | import { ValidationContainer } from "@fs/container/validation/ValidationContainer";
4 |
5 | import { Core1 } from "@test/core/Core1";
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:221:17)
at Object.<anonymous> (test/core/Core.spec.ts:2:1)
Is there a way to get jest/ts-jest include the @paths
while resolving imports?
Solution 1:[1]
jest can't honor tsconfig's path mapping as it's ts compiler time, so jest configuration should have corresponding modulenamemapper to resolve aliased paths.
Solution 2:[2]
I wanted to resolve modules paths starting with ~/
to my <baseUrl>/<moduleName>
.
Thank to OJ Kwon link I solved it with (give him point).
tsconfig.json
see module-resolution path-mapping doc
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"~/*": ["*"]
}
},
}
jest config
Then we need to tell jest
to resolve the paths too. It's done with the following config:
"moduleNameMapper": {
"~/(.*)": "<rootDir>/src/$1"
},
Solution 3:[3]
Add jest.config.js on root project folder with the content below.
const { pathsToModuleNameMapper } = require('ts-jest/utils')
const { compilerOptions } = require('./tsconfig')
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
modulePaths: [
'<rootDir>'
],
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Oleg Valter is with Ukraine |
Solution 2 | Édouard Lopez |
Solution 3 | FranSanchis |