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
- Use ts-jest's helper to build moduleNameMapper from tsconfig paths.
- Set the rootDir and prefix so mapped paths resolve.
- 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
NestJS ts-jest config / decorator metadata error in CIFix NestJS ts-jest errors in CI - ts-jest uses its own tsconfig, so decorators fail unless experimentalDecora…
NestJS "nest build" error TS with decorators / emitDecoratorMetadata in CIFix "nest build" TypeScript errors about decorators in CI - tsconfig is missing experimentalDecorators or emi…
NestJS TestingModule missing app.init() in CIFix NestJS TestingModule tests that fail because app.init() was never called in CI - guards, interceptors, an…