Can imports with question marks be handled in Jest?

14 Views Asked by At

In a JS/Webpack/Jest project, I am attempting to import SVG files using the syntax:

import imageUrl from './image.svg?url

(This style is recommended by SVGR in their documentation.)

However, when I attempt to run tests, I hit an issue with Jest:

● Test suite failed to run

    Cannot find module './image.svg?url' from 'src/components/Home/Home.jsx'

    Require stack:
      src/components/Home/Home.jsx
      src/components/App.jsx
      src/components/App.test.jsx

      3 | import ErrorBoundary from '../ErrorBoundary';
      4 | import Loading from '../Loading';
    > 5 | import imageUrl from './image.svg?url'

I have attempted to configure jest.config.ts to support these imports, e.g. with:

 transform: {
    '.+\\.(css|css!|styl|less|sass|scss|png|jpg|ttf|woff|woff2|svg\\?url)$': 'jest-transform-stub',

But this has no effect.

1

There are 1 best solutions below

0
Matt R On

I got it to work with Jest config along the lines of:

  moduleNameMapper: {
    '^(.+\\.svg)(\\?\\w+)$': '$1',

This issue is discussed in https://github.com/pd4d10/vite-plugin-svgr/issues/97