None of the answers worked. I configured and wrote my own transformer to make this work.
(0) Very important notes
Always clear jest cache or work without a cache, when making changes in jest.config.js or the transformer. Otherwise your changes will have no effect.
clear cache: add option --clearCache
to your test run.
run without cache: add option --no-cache
to your test run.
(1) Create a test case to verify the output and see what's going on:
file: /src/mytest.test.tsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import MySvg from '@src/mysvg.svg';
test('asdf', () => {
render(<MySvg/>);
screen.getByText("aaa"); // this WILL FAIL, so you'll see the output
});
(2) Configure jest
file: /jest.config.js
...
const exportConfig = {
transform: {
...
// ↓ configure: "for svg files, use `svgTransform.js`"
'^.+\\.(svg)$': '<rootDir>/.jest/svgTransform.js',
},
...
}
(3) Create the transformer
file: /.jest/svgTransform.js
const path = require('path');
module.exports = {
process(src, filename) {
const absPath = path.resolve(filename);
const code = `
const React = require('react');
module.exports = {
__esModule: true,
default: () => React.createElement('img', {
src: "${absPath}"
}),
};
`;
return { code };
},
};
(4) Lessons learned
Nothing works as expected. No docs, no AI. Every change is an adventure.
Most AI and internet says module.exports = ${filename}
or the like. The problem is, that the generated code will be </assets/your_file.svg/>
, which will not be a valid tag and therefore cause an error.
document.createElement
instead of React.createElement
does not work
default: () => <img ... />
` does not work