Jest 单元测试入门

Jest 单元测试入门

今天,咱们要讲的是 Jest 单元测试的入门知识。javascript

为什么要进行单元测试?

在学习 Jest 以前,咱们须要回答一个问题:为什么要进行单元测试?编写单元测试能够给你带来不少好处:java

  • 将测试自动化,无需每次都人工测试。
  • 变动检查,当代码发生重构,能够及时发现,并作出相应的调整。
  • 列举测试用例,能够帮你了解全部的边界状况。
  • 看成文档,若是你的测试描述足够详细,生成的测试报告甚至能够看成文档。
  • ……

总之,单元测试会让你的生活更加美好。正则表达式

使用 Jest 进行单元测试

编写测试一般都会基于某个测试框架,在众多测试框架中我选择了 Jest,不只由于我是个 React 开发者(React 与 Jest 都是 Facebook 出的),并且由于它确实简单好用。让咱们开始编写测试吧!npm

首先,安装 Jest:json

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);
});
相关文章
相关标签/搜索