2021-02-25 typescript jest

Resolving Typescript paths using Jest, and ts-jest

Today I ran into a problem while trying to write tests for modules written in Typescript which used paths configured in tsconfig.json and resolved during compile with tsconfig-paths:

resolving typescript paths

Jest was not able to resolve the dependencies imported by the module I wanted to test, and I was able to make it work by mapping again the paths I had mapped in tsconfig.json.

Here are the three folders mapped in tsconfig.json:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "domain/*": ["./domain/*"],
      "application/*": ["./application/*"],
      "infrastructure/*": ["./infrastructure/*"]
    }
  }
}

And here is how I mapped the same folders in jest.config.js:

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  rootDir: "./",
  moduleNameMapper: {
    "domain/(.*)$": "<rootDir>/src/domain/$1",
    "application/(.*)$": "<rootDir>/src/application/$1",
    "infrastructure/(.*)$": "<rootDir>/src/infrastructure/$1",
  },
};

Here is the output of Jest:

resolving typescript paths

Simple config, and yet a life saviour for Typescript based projects.

Thanks!

References