Skip to content
Latchkey

NestJS jest "Cannot find module '@app/...'" path alias (moduleNameMapper) in CI

jest resolves modules with Node resolution, which does not understand tsconfig paths. An alias like @app/users that tsc accepts fails in jest unless you map it with moduleNameMapper.

What this error means

Unit tests fail with "Cannot find module '@app/users' from 'src/...'" even though the same import compiles fine with tsc and nest build.

NestJS
Cannot find module '@app/users/users.service' or its corresponding type declarations.
      at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:...)

Common causes

jest does not read tsconfig paths

tsc maps @app/* via paths, but jest uses its own resolver and ignores tsconfig, so the alias is unknown.

moduleNameMapper is missing or out of sync

No mapping (or a stale one) means aliases added to tsconfig were never mirrored into the jest config.

How to fix it

Generate the mapper from tsconfig

  1. Use ts-jest's helper to build moduleNameMapper from tsconfig paths.
  2. Set the rootDir and prefix so mapped paths resolve.
  3. Re-run jest so aliases match tsc.
jest.config.js
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig.json');
module.exports = {
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }),
};

Map aliases explicitly

For the default Nest jest block in package.json, add an explicit mapping.

package.json
"moduleNameMapper": { "^@app/(.*)$": "<rootDir>/$1" }

How to prevent it

  • Generate moduleNameMapper from tsconfig so aliases never drift.
  • Keep one source of truth for path aliases (tsconfig) and derive the rest.
  • Run the jest suite in CI so alias breakage is caught immediately.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →