Jest 单元测试入门
今天,我们要讲的是 Jest 单元测试的入门知识。
为何要进行单元测试?
在学习 Jest 之前,我们需要回答一个问题:为何要进行单元测试?编写单元测试可以给你带来很多好处:
- 将测试自动化,无需每次都人工测试。
- 变更检查,当代码发生重构,可以及时发现,并做出相应的调整。
- 列举测试用例,可以帮你了解所有的边界情况。
- 当作文档,如果你的测试描述足够详细,生成的测试报告甚至可以当作文档。
- ……
总之,单元测试会让你的生活更加美好。
使用 Jest 进行单元测试
编写测试通常都会基于某个测试框架,在众多测试框架中我选择了 Jest,不仅因为我是个 React 开发者(React 与 Jest 都是 Facebook 出的),而且因为它确实简单好用。让我们开始编写测试吧!
首先,安装 Jest:
|
1
|
npm install --save-dev jest
|
然后,编写一个待测试的文件,以Stack类为例:
Stack.js
function Stack() {
// 私有变量 items,用于记录数组,对象不能直接操作
var items = [];
// 类方法 push,在数组末尾添加项,对象可以直接调用
this.push = function (element) {
items.push(element);
};
// 删除并返回数组末尾的项
this.pop = function () {
return items.pop();
};
}
接下来,编写一个测试文件 Stack.test.js:
Stack.test.js
// 导入 Stack
var Stack = require('./Stack');
test('Stack', function () {
// 实例化一个 stack 对象
var stack = new Stack();
stack.push(8);
// 期望 stack 最后一项是8
expect(stack.pop()).toBe(8);
});
然后,在 package.json 中添加:
"scripts": {
"test": "jest"
}
最后,打开命令行运行:
npm test
PASS Stack.test.js结果会在命令行中生成测试报告:
Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 0.386s Ran all test suites.
在上面的测试代码中有个 expect().toBe() 来判断结果是否是预期,这叫断言。
什么是断言?在程序设计中,断言(assertion)是一种放在程序中的一阶逻辑(如一个结果为真或是假的逻辑判断式),目的是为了标示与验证程序开发者预期的结果。除了expect().toBe()之外,其他常用的断言包括:断言简介
expect().toEqual():判断结果是否和预期等价。expect().toBeFalsy():判断结果是否为假。expect().toBeTruthy():判断结果是否为真。
普通匹配器
- toBe - toBe 使用 Object.is 来测试是否完全相等
- .not - 用来测试相反的用例
- .toEqual - 如果你想检查某个对象的值,请改用 toEqual。
toBe
最简单的测试值的方法是看是否精确匹配。
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
toEqual
如果你想检查某个对象的值,请改用 toEqual。
test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});
.not
用来测试相反的用例
test('null', () => {
const n = null;
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
});
布尔值匹配器
- toBeNull 只匹配 null
- toBeUndefined 只匹配 undefined
- toBeDefined 与 toBeUndefined 相反
- toBeTruthy 匹配任何 if 语句为真
- toBeFalsy 匹配任何 if 语句为假
test('null', () => {
const n = null;
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
expect(n).toBeFalsy();
});
test('zero', () => {
const z = 0;
expect(z).not.toBeNull();
expect(z).toBeDefined();
expect(z).not.toBeUndefined();
expect(z).not.toBeTruthy();
expect(z).toBeFalsy();
});
数字匹配器
- .toBeGreaterThan() - 大于
- .toBeGreaterThanOrEqual() 大于等于
- .toBeLessThan() - 小于
- .toBeLessThanOrEqual() - 小于等于
- .toBeCloseTo() - 浮点数比较
toBeGreaterThan、toBeGreaterThanOrEqual、toBeLessThan、toBeLessThanOrEqual
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe 和 toEqual 对于数字来说是一样的
expect(value).toBe(4);
expect(value).toEqual(4);
});
.toBeCloseTo()
对于比较浮点数的相等,应该使用 toBeCloseTo
test('两个浮点数字相加', () => {
const value = 0.1 + 0.2; // 0.30000000000000004
expect(value).toBe(0.3); // 这句会报错,因为 js 浮点数有舍入误差
expect(value).toBeCloseTo(0.3); // 这句可以运行
});
字符串匹配器
- toMatch - 正则表达式的字符
- .toHaveLength(number) - 判断一个有长度的对象的长度
toMatch
正则表达式的字符
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/);
});
.toHaveLength(number)
判断一个有长度的对象的长度
expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);
数组匹配器
- .toContain(item) - 判断数组是否包含特定子项
- .toContainEqual(item) - 判断数组中是否包含一个特定对象
.toContain
判断数组是否包含特定子项
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'beer',
];
test('购物清单(shopping list)里面有啤酒(beer)', () => {
expect(shoppingList).toContain('beer');
});
.toContainEqual(item)
可以判断数组中是否包含一个特定对象,类似 toEqual 与 toContain 的结合
function myBeverages() {
return [
{delicious: true, sour: false},
{delicious: false, sour: true}
]
}
test('is delicious and not sour', () => {
const myBeverage = {delicious: true, sour: false};
expect(myBeverages()).toContainEqual(myBeverage);
});