79704876

Date: 2025-07-17 13:19:19
Score: 1
Natty:
Report link

Jest 27.5.1

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.

(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

References

Reasons:
  • Blacklisted phrase (0.5): How can I
  • Blacklisted phrase (1): StackOverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • High reputation (-1):
Posted by: DarkTrick