Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 522
Ole Avatar asked Oct 17 '18 17:10

Ole


2 Answers

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"
},
like image 106
Édouard Lopez Avatar answered Oct 17 '22 21:10

Édouard Lopez


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>'
    ],
}
like image 27
FranSanchis Avatar answered Oct 17 '22 20:10

FranSanchis