我最近想学习如何为ReactJS编写测试。 使用this示例以及airbnb和facebook / jest上的各种配置,我试试了运气。
//.babelrc
{
"presets": [["es2015", { "modules": false }], "react"],
"env": {
"test": {
"presets": [["es2015"], "react"]
}
}
}
这是我的Foo.js文件,来自上述示例:
//Foo.js
import React, { PropTypes } from 'react';
const propTypes = {};
const defaultProps = {};
class Foo extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className='foo'>
Bar
</div>
);
}
}
Foo.propTypes = propTypes;
Foo.defaultProps = defaultProps;
export default Foo;
这是我的测试文件,也来自示例:
//Foo.test.js
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import Foo from './Foo';
describe('A suite', () => {
it('should render without throwing an error', () => {
expect(shallow(<Foo />).contains(<div className='foo'>Bar</div>)).toBe(true);
});
it('should be selectable by class "foo"', () => {
expect(shallow(<Foo />).is('.foo')).toBe(true);
});
it('should mount in a full DOM', () => {
expect(mount(<Foo />).find('.foo').length).toBe(1);
});
it('should render to static HTML', () => {
expect(render(<Foo />).text()).toEqual('Bar');
});
});
我不知道自己错过了什么。我查看了许多GitHub问题,以及SO问题和答案,但我无法解决这个问题。
当我运行npm test
时,这是我的输出:
D:\my-project>npm test --no-cache
> my-project@0.8.0 test D:\my-project
> jest
FAIL tests\Foo.test.js
● Test suite failed to run
D:/my-project/tests/Foo.test.js: Unexpected token (8:19)
6 | describe('A suite', () => {
7 | it('should render without throwing an error', () => {
> 8 | expect(shallow(<Foo />).contains(<div className='foo'>Bar</div>)).toBe(true);
| ^
9 | });
10 |
11 | it('should be selectable by class "foo"', () => {
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 2.089s
Ran all test suites.
npm ERR! Test failed. See above for more details.
所以Jest正在以某种方式工作,因为它正在运行测试,但不是我预期的正确方式。
简单的功能如:1 + 2 = 3正在成功运行测试。
我感谢社区的任何帮助。
谢谢