Jest/Enzyme SVG Sprites Unexpected Token <

社会主义新天地 提交于 2019-12-23 23:14:13

问题


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:


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"
}


来源:https://stackoverflow.com/questions/52481678/jest-enzyme-svg-sprites-unexpected-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!