Jest测试教程之二:matchers匹配器


在软件开发的过程中,测试的重要性就不用多说了。下面介绍JavaScript的测试框架Jest中的各种matchers(匹配器)。

Jest

Jest中的toBe匹配器

需要特别注意的是,toBe匹配器进行的是严格的比较。toBe将会调用Object.is来进行相等性比较。说具体些,就是比较:

  • 两个对象的属性值相等
  • 两个对象的内存地址相同

比如:如下测试将会通过:

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

但如下测试将会失败:

test('object equality', () => {
  const obj1 = {name: 'luosi'};
  expect(obj1).toBe({name: 'luosi'});
});

同时给出提示:

If it should pass with deep equality, replace "toBe" with "toStrictEqual"

使用not进行反向比较

可以监测两个对象/值是否不等:

test('2 + 2 != 5', () => {
  expect(2 + 2).not.toBe(5);
})

Jest中的toEqual匹配器

针对上面的问题,可以采用toEqual匹配器来进行比较:

test('object equality', () => {
  const obj1 = {name: 'luosi'};
  expect(obj1).toEqual({name: 'luosi'});
});

toEuqal匹配器将会监测对象/数组中的每个元素,如果所有元素都相等,则认为两个对象/数组是相等的。

Jest中是否为真的测试

我们可以使用如下的方法:

  • toBeNull
  • toBeUndefined
  • toBeDefined
  • toBeTruthy
  • toBeFalsy

例如:

test('null', () => {
  const n = null;
  expect(n).toBeNull();
  expect(n).toBeDefined();
  expect(n).not.toBeUndefined();
  expect(n).not.toBeTruthy();
  expect(n).toBeFalsy();
});

test('positive number', () => {
  const a = 1;
  expect(a).not.toBeNull();
  expect(a).toBeDefined();
  expect(a).not.toBeUndefined();
  expect(a).toBeTruthy();
  expect(a).not.toBeFalsy();
});

Jest中数值的测试

可以使用如下方法进行比较:

  • toBeGreaterThan
  • toBeGreaterThanOrEqual
  • toBeLessThan
  • toBeLessThanOrEqual
  • toBeCloseTo

例如:

test('3 + 5', () => {
  const value = 3 + 5;
  expect(value).toBeGreaterThan(3);
  expect(value).toBeGreaterThanOrEqual(7.5);
  expect(value).toBeLessThan(10);
  expect(value).toBeLessThanOrEqual(10);

  // 针对数值型变量间的比较,toBe和toEqual的作用是一样的
  expect(value).toBe(8);
  expect(value).toEqual(8);
});

需要注意的是,在进行浮点数运算的时候,toEqual/toBe可能会出错,比如:

test('浮点数间的比较', () => {
  const value = 0.1 + 0.2;
  expect(value).toBe(0.3);
  expect(value).toEqual(0.3);
});

其提示信息中给出了原因:

Expected: 0.3
Received: 0.30000000000000004

因此,这时需要使用toBeCloseTo来及进行比较:

test('浮点数间的比较', () => {
  const value = 0.1 + 0.2;
  expect(value).toBeCloseTo(0.3);
});

Jest中字符串的测试

主要使用toMatch以及not.toMatch进行比较,支持正则表达式:

test('No potter in String: Harry Potter', () => {
  expect('Harry Potter').not.toMatch(/potter/);
});

test('Potter in String: Harry Potter', () => {
  expect('Harry Potter').toMatch(/Potter/);
});

对集合进行的测试

这里主要使用toContain:

const team = [
  'George',
  'Lucas',
  'Terry',
  'Jessie'
];

test('Jessie in the team', () => {
  expect(team).toContain('Jessie');
  expect(new Set(team)).toContain('Jessie');
});

对异常进行测试

function transfer() {
  throw new Error('insufficient funds');
}

test('transfer money throws an Error', () => {
  expect(() => transfer()).toThrow();
  expect(() => transfer()).toThrow(Error);
  expect(() => transfer()).toThrow('insufficient funds');
  expect(() => transfer()).toThrow(/funds/);
});

更多的匹配器

请参考官网:https://jestjs.io/docs/expect


文章作者: 逻思
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 逻思 !
  目录