Jest 20 + Webpack 2 + React 15 – 图像导入问题

我试图testing显示图像的React组件,但我得到以下错误:

FAIL test/image.test.js ● Test suite failed to run [Obfuscated...]/assets/images/sample.png:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){     ^ SyntaxError: Invalid or unexpected token at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17) at Object.<anonymous> (src/components/image.js:3:18) at Object.<anonymous> (test/image.test.js:3:14) 

该组件非常简单

 import React from 'react'; import { Component } from 'react'; import image from '../assets/images/sample.png'; export default class Image extends Component { render() { return ( <div > <img src={image}/> </div> ); } } 

我试图用Jest来testing这个组件。 我在我的package.json文件中有以下configuration。

  "scripts": { "test": "./node_modules/jest/bin/jest.js", }, "jest": { "setupFiles": [ "./test/jest_setup.js" ], "snapshotSerializers": [ "./node_modules/enzyme-to-json/serializer" ], "moduleNameMapper": { "\\.(css|scss|less)$": "./configs/jest/styleMock.js", "\\.(png|jpg|gif|ttf|eot|svg)$": "./configs/jest/fileMock.js" }, "moduleDirectories": ["node_modules"] } 

我的jest_setup.js看起来像这样

 import { shallow, render, mount } from 'enzyme'; global.shallow = shallow; global.render = render; global.mount = mount; // Fail tests on any warning console.error = message => { throw new Error(message); }; 

最后我的testing看起来像这样

 import React from 'react'; import {shallow} from 'enzyme'; import Image from '../src/components/image'; test('image', () => { const image = shallow( <Image/> ); expect(image.text()).toEqual(''); }); 

我希望增加

 "moduleNameMapper": { "\\.(css|scss|less)$": "./configs/jest/styleMock.js", "\\.(png|jpg|gif|ttf|eot|svg)$": "./configs/jest/fileMock.js" }, 

会解决它,但我卡住了。