本系列是我的常用 koa 中间件使用笔记,防止忘记使用方法而作记录
Jest是Facebook开源的一套JavaScript测试框架, 它集成了断言、JSDom、覆盖率报告等开发者所需要的所有测试工具。
基本使用
安装jest后需要新建一个npm脚本
其中含义:runInBand 顺序执行、forceExit 强制退出、colors 输出上色
//package json
"scripts": {
"test": "jest --runInBand --forceExit --colors"
},
然后建立一个 test 的文件夹,jest 会自动寻找所有的名字为 *.test.js 的文件执行。
在demo.test.js输入以下内容:
function sun(a, b) {
return a + b;
}
//test是测试函数
test('测试sun函数', () => {
expect(sun(1, 3)).toBe(4); toBe判断是否等于
})
//jest 输出的结果
// PASS test/demo.test.js
// √ 测试sun函数 (3 ms)
// Test Suites: 1 passed, 1 total
// Tests: 1 passed, 1 total
// Snapshots: 0 total
// Time: 4.029 s
这样运行 npm run test 就能输出结果了。
其他常用断言函数
//常见断言方法
expect({a:1}).toBe({a:1})//判断两个对象是否相等
expect(1).not.toBe(2)//判断不等
expect({ a: 1, foo: { b: 2 } }).toEqual({ a: 1, foo: { b: 2 } })
expect(n).toBeNull(); //判断是否为null
expect(n).toBeUndefined(); //判断是否为undefined
expect(n).toBeDefined(); //判断结果与toBeUndefined相反
expect(n).toBeTruthy(); //判断结果为true
expect(n).toBeFalsy(); //判断结果为false
expect(value).toBeGreaterThan(3); //大于3
expect(value).toBeGreaterThanOrEqual(3.5); //大于等于3.5
expect(value).toBeLessThan(5); //小于5
expect(value).toBeLessThanOrEqual(4.5); //小于等于4.5
expect(value).toBeCloseTo(0.3); // 浮点数判断相等
expect('Christoph').toMatch(/stop/); //正则表达式判断
expect(['one','two']).toContain('one'); //不解释
如果判断object相等必须使用toEqual