官方网站: https://github.com/facebook/jest
基本用法
1. npm install --save-dev jest
2. 我们创建一个项目,包含3个文件:
2.1 package.json :
{
"name": "test_jest",
"version": "1.0.0",
"description": "this is test_jest project",
"author": "siwei",
"private": true,
"scripts": {
"test": "jest"
},
"dependencies": {},
"devDependencies": {
"jest": "^24.9.0"
},
"engines": {
"node": ">= 4.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
2.2 src/sum.js
function sum(a,b){
return a + b;
}
module.exports = sum;
2.3 test/sum.test.js
const sum = require('../src/sum')
test(' 1 + 2 = 3', () => {
expect(sum(1,2)).toBe(3)
})
3. 安装:
$ npm install --dev-save
4. 运行
$ npm run test
(这个命令会把当前目录下的所有 xx.test.js 的文件找到并且运行 )
结果如下
> test_jest@1.0.0 test /workspace/test_jest > jest PASS test/sum.test.js ✓ 1 + 2 = 3 (8ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.539s Ran all test suites.
Matcher
参考: https://jestjs.io/docs/en/using-matchers 以及https://jestjs.io/docs/en/expect
expect('..') 返回的叫做 期望 expectation
toBe(...) 则是叫做 matcher
用matcher的好处是, 可以打印出详细的log, (断点级别的信息都能看到, 虽然我这辈子都没用过断点)
我用的最多的是toBe, toEqual