Jest/Enzyme SVG Sprites Unexpected Token <

2019-07-14 11:45发布

I am having a problem creating a snapshot test with Jest and Enzyme on a component using SVG sprites.

I am using the package svg-sprite-loader: https://github.com/kisenka/svg-sprite-loader

Here is the component that's giving it trouble:

import React from 'react';
import dieIcons from '../../public/images/dieIcons.svg';

const DieIcon = (props) => (
<svg className={`die__icon icon-${props.name}`} onMouseDown={props.onMouseDown} onMouseUp={props.onMouseUp} onMouseOut={props.onMouseOut}>
   <use xlinkHref={`#dieIcons_${props.name}`} />
</svg>);

export default DieIcon;

Here is the Jest error:

Test suite failed to run

/home/ubuntu/workspace/tabletop-app/public/images/dieIcons.svg:2
<svg style="display:none;">
^

SyntaxError: Unexpected token <

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
  at Object.<anonymous> (src/components/DieIcon.js:2:17)
  at Object.<anonymous> (src/components/SingleRollDie.js:2:16)

I have tried to follow Jest's guidance on how to handle static assets like so:

// in package.json
"jest": {
    "moduleNameMapper": {
      "modulePaths": ["/shared/vendor/modules"],
      "moduleFileExtensions": ["js", "jsx"],
      "moduleDirectories": ["node_modules", "bower_components", "shared"],
      "\\.(svg)$": "<rootDir>/src/tests/__mocks__/fileMock.js"
    }
}

Lastly here is a link to my project's GitHub:https://github.com/deannellis/tabletop

1条回答
姐就是有狂的资本
2楼-- · 2019-07-14 12:07

This issue is happening because jest is not able to resolve SVG imports which I think in your projects are handled by webpack.

After a bit of reading, I came across the following package which is specifically meant for testing such imports.

Install this package:

npm install --save-dev identity-obj-proxy

Update your moduleNameMapper within jest.config to following:

moduleNameMapper: {
  ".+\\.(svg|png|jpg)$": "identity-obj-proxy"
}
查看更多
登录 后发表回答