Jest 遇到了意外的 token React
2019-03-20
2168
我有 2 个测试,第一个运行正常:sum.js:
function sum(a, b) {
return a + b;
}
module.exports = sum;
sum.test.js
const sum = require('./sum');
test('adds 2 + 5 to equal 7', () => {
expect(sum(2, 5)).toBe(7);
});
它运行正常,在控制台中打印消息。
第二个(我不确定)由 create-react-app 默认设置
App.test.js:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
ReactDOM.unmountComponentAtNode(div);
});
App.js :
import React, { Component } from 'react';
import {HashRouter} from "react-router-dom";
import Routes from './routes';
import Alerts from './app/components/alerts';
import Navbar from '../src/app/navbar/navbar'
import Auth from './app/settings/auth';
import Register from './app/entities/user/modify-modal';
import './index.scss';
class App extends Component {
componentWillMount(){
}
render() {
return (
<HashRouter>
<>
<Auth></Auth>
<Navbar></Navbar>
<Alerts></Alerts>
<Register/>
<div className={"content-root"}>
<Routes/>
</div>
</>
</HashRouter>
);
}
}
export default App;
package.json
{
"name": "x5_r_app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@babel/cli": "^7.2.3",
"@babel/plugin-proposal-class-properties": "^7.4.0",
"@babel/plugin-syntax-dynamic-import": "^7.2.0",
"@babel/preset-env": "^7.4.1",
"@babel/preset-flow": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"@fortawesome/fontawesome-free": "^5.7.1",
"@fortawesome/fontawesome-svg-core": "^1.2.12",
"@fortawesome/free-solid-svg-icons": "^5.6.3",
"@fortawesome/react-fontawesome": "^0.1.3",
"axios": "^0.18.0",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.5",
"bootstrap": "^4.2.1",
"jest": "^24.5.0",
"jest-cli": "^24.5.0",
"jsdom": "^14.0.0",
"moment": "^2.23.0",
"node-sass": "^4.11.0",
"react": "^16.7.0",
"react-addons-test-utils": "^15.6.2",
"react-bootstrap": "^1.0.0-beta.5",
"react-bootstrap-typeahead": "^3.2.4",
"react-datetime": "^2.16.3",
"react-debounce-input": "^3.2.0",
"react-dom": "^16.7.0",
"react-router-dom": "^4.3.1",
"react-scripts": "2.1.2",
"react-select": "^2.3.0",
"reactstrap": "^7.0.2",
"rxjs": "^6.3.3",
"scss": "^0.2.4",
"test": "^0.6.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"@babel/core": "^7.4.0",
"babel-core": "^6.26.3",
"babel-jest": "^24.5.0"
}
}
package-lock.json 有 20000 行代码,所以我不知道其中哪一部分需要解释我的问题,我读过的关于这个问题的所有指南对我来说都没用,所以我在这里问。
1个回答
问题在于,应用是使用
create-react-app
引导的,但随后也安装了最新版本的
Jest
,并且
package.json
中的
npm test
脚本已更改为直接启动
jest
。
测试失败,因为
Jest
未配置为转译 JSX 语法。
使用 JSX 等语法的测试必须先进行转译,然后才能由
Jest
运行。
create-react-app
包含
react-scripts
,它会自动处理所有这些配置。
如果应用是使用
create-react-app
引导的,则无需手动安装和配置
Jest
。
如果应用没有使用
create-react-app
引导,或者应用程序从
create-react-app
中弹出,则需要安装并配置
Jest
来转译测试代码。
Brian Adams
2019-03-20