Skip to content
Latchkey

Jest "Cannot find module" After Path Alias (moduleNameMapper) in CI

Jest does not read TypeScript paths. An alias like @/foo compiles fine with tsc but Jest cannot resolve it unless a matching moduleNameMapper entry exists.

What this error means

Type-check passes, but jest fails with Cannot find module '@/...' for every aliased import. The same imports work in the build because tsc honors paths.

node
Cannot find module '@/utils/format' from 'src/app.test.ts'

  3 | import { format } from '@/utils/format';
    |                         ^

Common causes

Jest has no moduleNameMapper for the alias

TypeScript paths only affect type-checking and tsc emit. Jest resolves modules itself and needs the alias mapped explicitly.

How to fix it

Add a moduleNameMapper entry

Map the alias prefix to the source directory in the Jest config.

jest.config.js
// jest.config.js
module.exports = {
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
};

Generate the mapper from tsconfig paths

Use a helper so the Jest mapping stays in sync with tsconfig automatically.

jest.config.ts
// jest.config.ts
import { pathsToModuleNameMapper } from 'ts-jest';
import { compilerOptions } from './tsconfig.json';

export default {
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths, {
    prefix: '<rootDir>/',
  }),
};

How to prevent it

  • Derive Jest moduleNameMapper from tsconfig paths so they cannot drift.
  • Run the test suite in CI on a clean checkout, not only the type-check.
  • Keep alias definitions in one place and reference it everywhere.

Related guides

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