使用官方的例子跑起来是没问题的,但官方使用的是ES5的语法,没有没有使用ES6最新语法,尝试了一下是不行的,在google借鉴了各种办法才找出解决方案,记录一下。
模拟例子
package.json文件
{
"name": "create-react-app",
"version": "1.0.0",
"private": true,
"dependencies": { "jss": "latest", "jss-preset-default": "latest", "material-ui": "next", "prop-types": "latest", "react": "latest", "react-dom": "latest", "react-jss": "latest", "react-scripts": "latest", "recompose": "latest" },
"scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "jest", "eject": "react-scripts eject" },
"devDependencies": { "babel-jest": "^21.0.2", "babel-preset-es2015": "^6.24.1", "babel-preset-react": "^6.24.1", "enzyme": "^2.9.1", "expect": "^21.1.0", "jest": "^21.1.0", "jest-cli": "^21.1.0", "react-test-renderer": "^15.6.1" },
"jest": { "collectCoverage": true, "testMatch": [ "**/__tests__/**/*.js?(x)" ], "moduleDirectories": [ "node_modules", "src" ], "testPathIgnorePatterns": [ "/node_modules/" ] } }
React组件
import React from 'react';
const STATUS = {
HOVERED: 'hovered',
NORMAL: 'normal',
};
class Link extends React.Component {
// state = {无法使用
// class:'asdf'
// };
constructor(props) {
super(props);
this._onMouseEnter = this._onMouseEnter.bind(this);
this._onMouseLeave = this._onMouseLeave.bind(this);
this.state = {
class: STATUS.NORMAL,
open:true
};
}
_onMouseEnter () { // = () => 也无法使用
this.setState({class: STATUS.HOVERED});
}
_onMouseLeave () {
this.setState({class: STATUS.NORMAL});
}
render() {
return (
<a
className={this.state.class}
href={this.props.page || '#'}
onMouseEnter={this._onMouseEnter}
onMouseLeave={this._onMouseLeave}>
{this.props.children}
</a>
);
}
}
export default Link
Jest测试
import React from 'react';
import Link from '../src/mycomp/Link';
import renderer from 'react-test-renderer';
describe('Shallow Rendering', function () {
it('App\'s title should be Todos', function () {
const component = renderer.create(
<Link page="http://www.facebook.com">Facebook</Link>
);
let tree = component.toJSON();
expect(tree.type).not.toBe("b");
expect(tree).toMatchSnapshot();
});
});
运行jest
命令出现以下错误
● Test suite failed to run
/Users/huanghuanlai/dounine/github/material-ui/examples/create-react-app/src/mycomp/Link.js: Unexpected token (10:7)
8 | class Link extends React.Component {
9 |
> 10 | state = {
| ^
11 | class:'asdf'
12 | };
函数简写异常
FAIL __tests__/Link.js
● Test suite failed to run
/Users/huanghuanlai/dounine/github/material-ui/examples/create-react-app/src/mycomp/Link.js: Unexpected token (31:15)
29 | }
30 |
> 31 | _onMouseLeave = () => {
| ^
32 | this.setState({class: STATUS.NORMAL});
33 | }
解决方案
安装babel-preset-stage-2
组件
npm install --save-dev babel-preset-stage-2
修改.babelrc
配置文件
{
"presets": ["es2015", "react", "stage-2"] }