Enzyme: Issues when using with require

Created on 12 Apr 2017  路  6Comments  路  Source: enzymejs/enzyme

Using const InlineSVG = require("svg-inline-react"); to render SVG

I am testing a component which renders:

return dom.div(
    {
      className: buttonClass ? `close-btn ${buttonClass}` : "close-btn",
      onClick: handleClick,
      title: tooltip
    },
    Svg()
  );

Svg() is another wrapper which renders

props = { src: require("./close.svg") }
return React.createElement(InlineSVG, props);

I use this code to test:

const wrapper = shallow(new CloseButton({ handleClick: onClick }));
console.log(wrapper.debug());

I am getting this error:
since the src is {} instead of being a string.

console.error ../node_modules/fbjs/lib/warning.js:36
    Warning: Failed prop type: Invalid prop `src` of type `object` supplied to `InlineSVG`, expected `string`.
        in InlineSVG

But require() works well when I normally run the application.

Most helpful comment

@AnshulMalik Can you post your solution please?

All 6 comments

You can't require svg by default. Whatever you use in your app to hack that in (webpack, I assume) needs to also run with your tests.

Yes @ljharb we use webpack for that, can you please guide me on how can I use webpack with this ?
Or gimme a link where I can find more detailed information.

Got it working. Thanks @ljharb
Not any issue with enzyme :)

@AnshulMalik Can you post your solution please?

Got it working. Thanks @ljharb
Not any issue with enzyme :)

I have the same problem with you.
Can you post your solution please?
Thanks.

If you are using jest you can handle it by adding in jest.config.js file

moduleNameMapper: { 
  '\\.svg$': '<rootDir>/assets/mocks/svgMock.js', 
} 

svgMock.js contain module.exports = "";

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thurt picture thurt  路  3Comments

ivanbtrujillo picture ivanbtrujillo  路  3Comments

blainekasten picture blainekasten  路  3Comments

aweary picture aweary  路  3Comments

AdamYahid picture AdamYahid  路  3Comments