Skip to content
Latchkey

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.

Jest output
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
// 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

  1. If you import SVGs as React components, add a transformer like jest-transformer-svg.
  2. Keep identity-obj-proxy for CSS Modules so styles.card returns the string "card".
  3. Restart with --no-cache after 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-proxy so CSS-Module class lookups stay meaningful.
  • Keep the mapper’s extension list in sync with what the bundler handles.

Frequently asked questions

What causes "CSS/asset import fails"?
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.
How do I fix CSS/asset import fails?
Point style and file imports at lightweight mocks so the component can mount without the real asset.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card