Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ignore "-!svg-react-loader!./path/to/my.svg" when testing with Jest without bundling everything with webpack

We're using svg-react-loader for some of the SVG files in our application. We're trying to setup jest to run with a babel-jest and the following .babelrc:

{
  "presets": [
    "es2015", 
    "react"
  ],
  "plugins": [
    "transform-decorators-legacy", 
    "transform-class-properties",
    "transform-object-rest-spread"
  ]
}

The following test fails:

/* global it, document */
import React from 'react'
import ReactDOM from 'react-dom'
import Comp from './Icon'

it('renders without crashing', () => {
  const div = document.createElement('div')
  ReactDOM.render(<Comp><div /></Comp>, div)
})

With error: Cannot find module '-!svg-react-loader!../../assets/grid.svg' from 'Icon.js'

How could I ignore imports that start with like import grid from '-!svg-react-loader!../../assets/grid.svg' in jest?

like image 463
Vlad Nicula Avatar asked Nov 18 '25 07:11

Vlad Nicula


2 Answers

The way I solved this was by adding a jest mock for any import that contains -!svg-react-loader! at the beginning of the module.

"moduleNameMapper": {
   "^-!svg-react-loader.*$": "<rootDir>/config/jest/svgImportMock.js"
}

Where svgImportMock.js is:

'use strict';
module.exports = 'div';

It's not ideal, because the file could simple not exists, but the assumption is that we see the missing module when bundling with webpack.

like image 136
Vlad Nicula Avatar answered Nov 20 '25 20:11

Vlad Nicula


I resolved this by installing jest-svg-transformer, then adding this config:

{ "jest": { "transform": { "^.+\\.svg$": "jest-svg-transformer" } } }

like image 23
David Calhoun Avatar answered Nov 20 '25 22:11

David Calhoun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!