前言
作为一个项目而言,单元测试应该是必备的一部分,也是最容易被大家忽略的一部分,这篇文章就介绍一下jest 和 enzyme。
Jest 特点:
- 测试用例并行执行,更高效
- 强大的 Mock 功能
- 内置的代码覆盖率检查,不需要在引入额外的工具
- 集成 JSDOM,可以直接进行 DOM 相关的测试
- 更易用简单,几乎不需要额外配置
- 可以直接对 ES Module Import 的代码测试
- 有快照测试功能,可对 React 等框架进行 UI 测试
开发
- 安装jest
npm install jest babel-jest enzyme enzyme-adapter-react-16
我们先写个列子试一下,在tests
文件夹下创建demo.js
和 demo.test.js
// demo.js
function sum(a, b){
return a + b;
}
module.exports = sum;
// demo.test.js
const sum = require('./sum.js')
test('test 1 plus 2 result', () => {
expect(sum(1 , 2)).toBe(3);
})
test('test 2 plus 2 should equal 4', () => {
expect(sum(2 , 2)).toBe(4);
})
在package.json
的 script 中加入
"test": "jest"
我们运行npm run test
看下效果
- 让我们写个简单的UI测试
在routes
中创建Demo2.jsx
import React from 'react';
export default class CheckboxWithLabel extends React.Component {
constructor(props) {
super(props);
this.state = { isChecked: false };
this.onChange = this.onChange.bind(this);
}
onChange() {
this.setState({ isChecked: !this.state.isChecked });
}
render() {
return (
<label>
<input
type="checkbox"
checked={this.state.isChecked}
onChange={this.onChange}
/>
{this.state.isChecked ? this.props.labelOn : this.props.labelOff}
</label>
);
}
}
在tests
中创建`demo2.test.js
import React from 'react'
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { shallow } from 'enzyme'
import Demo from '../src/routes/Test.jsx'
configure({ adapter: new Adapter() });
test('CheckboxWithLabel changes the text after click', () => {
const checkbox = shallow(<Demo labelOn="On" labelOff="Off" />);
expect(checkbox.text()).toEqual('Off');
checkbox.find('input').simulate('change');
expect(checkbox.text()).toEqual('On');
});
我们运行npm run test
来看下效果
PS F:\mytest\react-architecture> npm run test
> react-architecture@1.0.0 test F:\mytest\react-architecture
> jest
PASS tests/demo.test.js
PASS tests/demo2.test.js
Test Suites: 2 passed, 2 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 2.402s
Ran all test suites.
好,我们吧demo2.test.js
的 expect(checkbox.text()).toEqual('Off');
和expect(checkbox.text()).toEqual('On');
换下位置,会出现什么呢?
PS F:\mytest\react-architecture> npm run test
> react-architecture@1.0.0 test F:\mytest\react-architecture
> jest
FAIL tests/demo2.test.js
● checkbox change
expect(received).toEqual(expected)
Expected value to equal:
"On"
Received:
"Off"
8 | test('checkbox change', () => {
9 | const checkbox = shallow(<Demo labelOn="On" labelOff="Off" />);
> 10 | expect(checkbox.text()).toEqual('On');
| ^
11 |
12 | checkbox.find('input').simulate('change');
13 |
at Object.<anonymous> (tests/demo1.test.js:10:29)
PASS tests/demo.test.js
Test Suites: 1 failed, 1 passed, 2 total
Tests: 1 failed, 2 passed, 3 total
Snapshots: 0 total
Time: 2.325s
Ran all test suites.
总结
这篇文章我们介绍了在项目中加入单元测试, 简单写了一些测试例子。