运行测试时,它会在代码中显示“意外的令牌错误:
const wrapper = shallow(<WelcomeMessage/>");
该错误抛出“(<”。我已经查看了来自stackoverflow和github的许多答案,但是不知何故我仍然无法使其正常工作。
我写了笑话测试。这是我第一次使用酶和反应编写测试用例。因此,我不熟悉该设置。我已经安装了:babel开玩笑,react-dom,babel-plugin-transform-export-extensions,enzyme-adapter-react-16,react-test-renderer,@ babel / preset-env和@ babel / core
package.json:
{
"private": true,
"version": "0.0.0",
"name": "example-jquery",
"devDependencies": {
"@babel/core": "*",
"@babel/preset-env": "^7.4.4",
"babel-jest": "^24.8.0",
"babel-plugin-transform-export-extensions": "^6.22.0",
"enzyme": "^3.9.0",
"enzyme-adapter-react-16": "^1.12.1",
"jest": "^24.8.0",
"jest-dom": "^3.1.4",
"jest-useragent-mock": "0.0.3"
},
"dependencies": {
"jest-puppeteer": "^4.1.1",
"jquery": "^3.4.1",
"jsdom": "^15.0.0",
"puppeteer": "^1.15.0",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-test-renderer": "^16.8.6"
},
"scripts": {
"test": "jest --verbose"
},
"jest": {
"transform": {
"^.+\\.jsx?$": "babel-jest"
}
}
}
jest.config.js:
module.exports = {
preset: 'jest-puppeteer',
"bail": 0,
setupFiles: ['<rootDir>/enzyme.config.js'],
moduleFileExtensions: ['js', 'json', 'jsx'],
transformIgnorePatterns: ['<rootDir>/node_modules/']
}
enzyme.config.js:
const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');
Enzyme.configure({ adapter: new Adapter() });
.babelrc:
{
"presets": ["@babel/preset-env"],
"plugins": ["transform-export-extensions"],
"only": [
"./**/*.js",
"node_modules/jest-runtime"
]
}
WelcomeMessage.test.js:
import React from 'react';
import { shallow } from 'enzyme';
// Components
import WelcomeMessage from './WelcomeMessage';
function setup() {
const props = {
imgPath: 'some/image/path/to/a/mock/image',
};
const wrapper = shallow(<WelcomeMessage />);
return { wrapper, props };
}
describe('WelcomeMessage Test Suite', () => {
it('Should have an image', () => {
const { wrapper } = setup();
expect(wrapper.find('img').exists()).toBe(true);
});
});
答案 0 :(得分:1)
此行:
<WelcomeMessage />
是JSX,"just provides syntactic sugar for the React.createElement
function"。
由于JSX实际上不是有效的JavaScript代码,因此必须将其编译为React.createElement
个调用。
这是通过Babel
插件@babel/plugin-transform-react-jsx
完成的,该插件是@babel/preset-react
的一部分。
将@babel/preset-react
添加到您的Babel
配置中,即可解决此问题。