In a Jest test suite, why does importing '@/lib/price' or a .css file fail when the app builds fine, and how does moduleNameMapper fix it?
answer
- Jest resolves modules on its own
- regex keys and $1 backreferences
- a stub module for styles
- first matching key wins
basics
~10 sJest resolves modules itself and reads neither the tsconfig paths nor the bundler's aliases and CSS loaders. moduleNameMapper maps request regexes to replacements, such as '^@/(.*)$' to '<rootDir>/src/$1' and '\.css$' to a stub module.
solid answer
~40 sJest has its own module resolver and does not read `tsconfig.json` `paths` or a bundler's alias and loader settings. So an alias import fails with `Cannot find module '@/lib/price' from 'src/card.test.js'`, and an imported stylesheet reaches the JavaScript parser and fails with `Jest encountered an unexpected token`. `moduleNameMapper` maps regular expressions, matched against the requested module name, to a replacement path or an array of paths tried in order. Captured groups are substituted with `$1`, and `<rootDir>` stands for the project root: `'^@/(.*)$': '<rootDir>/src/$1'`. Styles and images map to a stub module, for example `'\\.(css|less)$': '<rootDir>/test/style-stub.js'`. Keys are tried in the order written and the first match wins, so put specific keys first and anchor them with `^` and `$`; an unanchored key matches any name that contains it.
code
javascript · 17 lines// jest.config.js
const {defineConfig} = require('jest');
module.exports = defineConfig({
moduleNameMapper: {
// most specific first: anchored alias, then assets
'^@/(.*)$': '<rootDir>/src/$1',
'\\.(css|less)$': '<rootDir>/test/style-stub.js',
'\\.(png|jpg|svg|woff2)$': '<rootDir>/test/file-stub.js',
},
});
// test/style-stub.js
module.exports = {};
// test/file-stub.js
module.exports = 'test-file-stub';go deeper
Recall that Jest does not understand path aliases or CSS imports by itself and that moduleNameMapper maps them.
Explain regex keys, $1 substitution, the rootDir token, first-match ordering and why keys need anchors.
Read the two resolution errors to tell a missing rule from a wrong target, and keep aliases generated from one source so tests and build cannot drift.
Set a monorepo convention for aliases and asset stubs that every package shares, so a new package does not reinvent its Jest resolution.
## Why the app works and the tests do not An application build resolves imports through the bundler and the TypeScript compiler: `paths` in `tsconfig.json` turns `@/lib/price` into `src/lib/price`, and a style loader turns `import './card.css'` into something the page can use. **Jest uses neither.** It has its own resolver, which starts from Node's rules plus its own options, and it executes every imported file as JavaScript. Two failures follow: ```plaintext Cannot find module '@/lib/price' from 'src/card.test.js' ``` for the alias, because nothing tells Jest what `@/` means, and ```plaintext Jest encountered an unexpected token ``` for the stylesheet, because CSS is not JavaScript. Jest's own hint for that error suggests stubbing non-JS modules with `moduleNameMapper`. ## How `moduleNameMapper` works `moduleNameMapper` (default `null`) is an object whose **keys are regular expressions** tested against the requested module name and whose **values are the module to load instead**, or an array of candidates. - **Backreferences**: `$1`, `$2` and so on substitute captured groups. - **`<rootDir>`**: the token stands for the project's root directory, so the mapping works on every machine. - **Arrays**: with `'assets/(.*)': ['<rootDir>/images/$1', '<rootDir>/photos/$1']`, Jest uses the first candidate that exists. - **Order**: patterns are checked one by one until one fits, so the most specific rule goes first. The same applies within an array. - **Anchors**: without `^` and `$`, a key matches any name that **contains** it; a key `relay` would also redirect `react-relay` and `graphql-relay`. - **Mocking**: modules mapped this way are unmocked by default, even when automocking is on. ## The two everyday mappings 1. **Path aliases.** Mirror each alias from the build config: `'^@/(.*)$': '<rootDir>/src/$1'`. If the target is wrong, Jest says so precisely: `Could not locate module @/lib/price mapped as: ...`, followed by the `moduleNameMapper` entry it used, which points straight at the faulty rule. 2. **Styles and static assets.** Map them to small stub modules, for example `'\\.(css|less)$'` to a file exporting `{}`, and image or font extensions to a file exporting a string. Tests then import components without loading real assets. When a component reads class names from a CSS module, a Proxy-based stub such as `identity-obj-proxy` returns each key as its own name, so `styles.title` is `'title'`. ## Mapper, transform or resolver options? | Need | Option | Why | |---|---|---| | Replace what an import **resolves to** | `moduleNameMapper` | matches the request string and swaps the target | | Turn a file's **contents** into JavaScript | `transform` | matches the file path and compiles the source | | Search **extra folders** for bare names | `modulePaths` or `moduleDirectories` | adds lookup locations, does not rewrite prefixes | A common wrong turn is adding a `transform` entry for `@/`: transform keys match file paths after resolution, so they never see the alias. Another is `modulePaths: ['<rootDir>/src']`, which lets `lib/price` resolve but still leaves `@/lib/price` unknown. The Jest docs also discourage adding `'.'` to `moduleDirectories` and recommend `moduleNameMapper` instead. ## A worked example In a TypeScript monorepo, the web package's `Card` component imports `@/lib/price` for formatting and `./card.css` for its styles. Its test fails twice in a row: first on the alias, then, once the alias is mapped, on the stylesheet. With both rules in place, the stylesheet resolves to a module exporting `{}` and the alias resolves to `packages/web/src/lib/price`, so the test exercises the component's logic without any build tooling. The API package needs neither rule, which is one reason to keep these mappings in the web project rather than in a shared root config. ## Keeping it maintainable - Keep the alias table in one place. A TypeScript monorepo can generate `moduleNameMapper` from the same alias list the build uses, so the two cannot drift. - In a `projects` config each project has its own `rootDir`, so `<rootDir>/src/$1` resolves inside that package. - Run `jest --showConfig` to see the mapper after presets and project settings are applied. - Mapping a whole dependency to a stub hides real behaviour; keep stubs for assets and use the module-mocking API when a test needs a fake implementation.
- A Jest moduleNameMapper key is written as 'relay' without anchors; what goes wrong?Keys are regular expressions tested against the module name, so an unanchored `relay` matches any name containing it: `relay`, `react-relay` and `graphql-relay` all load the stub. Anchor the key, `'^relay$'`, and list specific keys before general ones, because the first matching key wins.
- How do you tell a wrong mapping target apart from a missing mapping in Jest?With no matching key, Jest reports `Cannot find module '@/lib/price' from '...'`. With a key that matches but points at a missing file, it reports `Could not locate module @/lib/price mapped as: ...` and prints the `moduleNameMapper` entry it used, so the fix is in that rule's replacement path.
moduleNameMapper works like a mail-forwarding list at a post office: each incoming address is checked against the rules from the top, and the first rule that matches decides where the letter goes. A rule written too loosely, such as everything containing 'relay', forwards mail that was never meant for it.
- Jest reads tsconfig paths automatically, so aliases need no Jest configuration.
- A transform entry for '^@/' rewrites alias imports during compilation.
- moduleNameMapper keys are matched as exact module names, not regular expressions.
- When two keys match, Jest picks the longest one regardless of order.
- A CSS import fails because jsdom cannot parse stylesheets.