我正在尝试测试显示图像的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测试此组件。我在package.json
文件中有以下配置。
"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);
};
最后我的测试看起来像这样
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"
},
会解决它,但我被困住了。