ImageToSVG

Mocking SVG Imports in Jest

Jest can't parse SVG files natively — here's how to mock them so component tests importing SVGs don't fail.

Preset:
Colors:
VTracer vectorization + SVGO optimizationPrivacy protected

Why SVG Imports Break Jest by Default

Jest runs in Node, which has no native understanding of SVG-as-component or SVG-as-URL import syntax that bundlers like Webpack or Vite provide — without configuration, `import Logo from './logo.svg'` throws a syntax error the moment Jest tries to parse the file.

  • Jest's Node environment can't parse SVG import syntax natively
  • Unconfigured SVG imports throw immediate test-run syntax errors
  • This affects any component test importing an SVG, even indirectly

Configuring the Mock

Add a `moduleNameMapper` entry in `jest.config.js` mapping `\.svg$` to a mock module — either a simple string stub (`'<svg-mock />'`) or the `jest-transform-stub` package, which returns a generic component placeholder. This lets tests import components using SVGs without Jest needing to actually parse the file's contents.

  • moduleNameMapper redirects .svg imports to a mock module
  • jest-transform-stub provides a ready-made generic stub
  • Tests verify component logic without needing real SVG content

Frequently Asked Questions

Will mocking SVGs hide real bugs in my icon components?

For most component logic tests, no — you're typically testing behavior (clicks, state, props) rather than the SVG's visual content, which a mock stub doesn't affect. Visual correctness belongs to snapshot or visual regression testing instead.

Does this configuration differ between Create React App and custom Jest setups?

CRA includes SVG mocking out of the box via its preset Jest config. Custom Jest setups (Vite + Vitest, or hand-configured Jest) need the moduleNameMapper entry added explicitly.

Related guides

Ready to Convert Your Image to SVG?

Free online converter — no sign-up, no watermarks, results in under 3 seconds.

Try It Free — Convert Image to SVG