Jest "Unexpected token" on CSS/SVG Imports - moduleNameMapper
A component imports a CSS file, SVG, or image. Jest only understands JavaScript, so when your bundler-handled asset import reaches Jest it either throws a syntax error or pulls real file contents into the module graph.
What this error means
A component test fails the moment it imports a .css/.scss or an image/SVG, with an unexpected-token error on the asset’s contents. The component renders fine in the app because the bundler handles those imports - Jest does not.
SyntaxError: Unexpected token '.'
> 1 | .card { display: flex; }
| ^
at Runtime._execModule (node_modules/jest-runtime/build/index.js)Common causes
Jest has no loader for non-JS assets
Webpack/Vite turn CSS and images into modules, but Jest evaluates them as JavaScript. The raw CSS or binary content is not valid JS and fails to parse.
No stub mapped for the asset extension
Without a moduleNameMapper entry, the import resolves to the real file. CSS modules also need a value to destructure class names from, or the component crashes.
How to fix it
Map asset imports to stubs
Point style and file imports at lightweight mocks so the component can mount without the real asset.
// jest.config.js
module.exports = {
moduleNameMapper: {
'\\.(css|less|scss|sass)$': 'identity-obj-proxy',
'\\.(png|jpg|svg)$': '<rootDir>/test/fileMock.js',
},
};
// test/fileMock.js
module.exports = 'test-file-stub';Use a transform for SVG-as-component
- If you import SVGs as React components, add a transformer like
jest-transformer-svg. - Keep
identity-obj-proxyfor CSS Modules sostyles.cardreturns the string "card". - Restart with
--no-cacheafter editing the mapper so stale transforms clear.
How to prevent it
- Centralize asset mocks in the Jest config from the first component test.
- Use
identity-obj-proxyso CSS-Module class lookups stay meaningful. - Keep the mapper’s extension list in sync with what the bundler handles.