纵横研究院React技术专题社区

jest入门以及常用匹配器

2019-05-31  本文已影响3人  Qummy

简介

Jest有以下的特点:

安装

安装jest依赖包

npm install --save-dev jest

新建一个sum.js文件,作为测试的示例:

function sum(a, b) {
    return a + b;
}
module.exports = sum;

新建sum.test.js文件,写关于测试sum.js代码:

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

为了便于启动可以在package.json中配置命令:

{
  "scripts": {
    "test": "jest"
  }
}

最后,执行命令:

npm run test

常用匹配器

匹配器是为了去测试输入输出的值是否符合预期。

普通匹配器

toBe()

test('two plus two is four', () => {
  expect(2 + 2).toBe(4);
});

toBe用的是JavaScript中的Object.is(),属于ES6中的特性,所以不能检测对象,如果要检测对象的值的话,需要用到toEqual。toEquel递归检查对象或者数组中的每个字段。

test('object assignment', () => {
  const data = {one: 1};
  data['two'] = 2;
  expect(data).toEqual({one: 1, two: 2});
});
Truthiness

当需要区分undefined、null和false时:

数字匹配器

大多数的比较数字有等价的匹配器。

例子如下:

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 and toEqual are equivalent for numbers
  expect(value).toBe(4);
  expect(value).toEqual(4);
});

如果使用toBe就会产生以下结果:

test('两个浮点数字相加', () => {
  const value = 0.1 + 0.2;
  <!-- expect(value).toBe(0.3);           这句会报错,因为浮点数有舍入误差 -->
  expect(value).toBeCloseTo(0.3); // 这句可以运行
});
字符串

使用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/);
});
数组

如何检测数组中是否包含特定某一项?可以使用toContain()

const shoppingList = [
  'diapers',
  'kleenex',
  'trash bags',
  'paper towels',
  'beer',
];

test('(shopping list)里面有(diapers)', () => {
  expect(shoppingList).toContain('beer');
});
上一篇 下一篇

猜你喜欢

热点阅读