Jest fails when a component imports an .svg file
A test fails as soon as a component that imports an .svg file is loadedShort answer
Jest runs every imported file as JavaScript, and an .svg file is XML, not JavaScript. Tell Jest what to do with it: map .svg imports to a small stub module with moduleNameMapper, or give them a transformer. If you add a transform, list babel-jest again, because a custom transform replaces the default one.
Fix it fast
1Find out which cause you have
Read the first lines of the failure. The file named in the stack and the line it points at show whether Jest is parsing the SVG as code or cannot find it.
npx jest --no-cache 2>&1 | head -402Match what you see, then jump to its fix
- 1
The stack points into the .svg file, or a syntax error appears on the first line of itJest has no rule for .svg filesFix - 2
The error stays after you added a ruleThe mapper pattern is wrong or sits below a broader ruleFix - 3
SVG imports work, but JSX or TypeScript files now fail to parseA custom transform replaced babel-jestFix
- 1
What does the error look like?
A test fails as soon as a component that imports an .svg file is loadedA syntax error is reported for the .svg file, because Jest tries to parse it as JavaScript
Cause 1 of 3
Jest has no rule for .svg files
1Check
By default Jest only transforms JavaScript and TypeScript files. An image is not valid JavaScript, so Jest needs a stub or a transformer for it.
cat jest.config.js 2>/dev/null; grep -n '"jest"' package.json2Fix
Map images to a stub file. The stub only needs to export something.
// jest.config.js
module.exports = {
moduleNameMapper: {
'\\.(svg|png|jpg|jpeg|gif|webp)$': '<rootDir>/__mocks__/fileMock.js',
},
};
// __mocks__/fileMock.js
module.exports = 'test-file-stub';3Verify
Run the test that imports the component.
npx jest src/App.test.jsConfirmed by jestjs.io
Cause 2 of 3
The mapper pattern is wrong or sits below a broader rule
1Check
moduleNameMapper checks patterns one by one in order, so a pattern listed earlier can take the import before yours. A pattern without ^ and $ boundaries also matches more than you mean.
grep -n -A8 moduleNameMapper jest.config.js2Fix
Put the specific svg rule first and anchor broad patterns.
moduleNameMapper: {
'\\.svg$': '<rootDir>/__mocks__/fileMock.js',
'^@/(.*)$': '<rootDir>/src/$1',
}3Verify
Run the failing test again.
npx jestConfirmed by jestjs.io
Cause 3 of 3
A custom transform replaced babel-jest
1Check
The default transform is babel-jest for .js, .jsx, .ts and .tsx files. Once you set the transform option yourself, that default is gone unless you list it.
grep -n -A6 "transform" jest.config.js2Fix
Add babel-jest back next to the svg transformer.
transform: {
'\\.[jt]sx?$': 'babel-jest',
'\\.svg$': '<rootDir>/fileTransformer.js',
},3Verify
Run the whole suite.
npx jestConfirmed by jestjs.io
How do I stop it coming back?
- Add the asset stub to the Jest config the day you add the first image import.
- Keep one jest.config.js; avoid a second config inside package.json.
- When you change the transform option, rerun the full suite once, not only the failing file.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- QistLockA NestJS and React SaaS driving an Android Device Owner agent that locks financed phones when payments lapse.
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
Related fixes
Web apps
Electron app blank with 'Refused to evaluate a string as JavaScript'
Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive
The page has a Content-Security-Policy without 'unsafe-eval', and some code calls eval or new Function.
3 causes, each with a fixWeb apps
A React component crashes while destructuring props or state
TypeError: Cannot destructure property 'b' of 'null' as it is null.
JavaScript throws this when the right side of a destructuring pattern is undefined or null.
3 causes, each with a fixWeb apps
Jest fails to parse a React Native or Expo dependency
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax
Jest does not run Babel on node_modules by default, and many React Native packages ship untranspiled source.
3 causes, each with a fixWeb apps
Sentry: Non-Error promise rejection captured with value in a React app
Non-Error exception (or promise rejection) captured with keys: x, y, z
Sentry raises this event when something that is not an Error object is thrown or used to reject a promise, for example a plain object from an API.
3 causes, each with a fixWeb apps
fetch() throws TypeError: Failed to fetch in the browser
Uncaught (in promise) TypeError: Failed to fetch
Failed to fetch means the request never produced a response the browser would hand to your code.
4 causes, each with a fixWeb apps
TypeScript says a JavaScript module implicitly has an any type
Could not find a declaration file for module 'react-materialize'. 'path/to/module-name.js' implicitly has an 'any' type.
TypeScript found the JavaScript file but no types for it, and noImplicitAny turns that into an error.
2 causes, each with a fix