【Jest】笔记二:Matchers匹配器

时间:2023-03-09 01:18:24
【Jest】笔记二:Matchers匹配器

一、前言

  什么是匹配器?

  我们可以把匹配器看成,testng断言,这么理解就可以了

二、常用的匹配器

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

在此代码中,expect (2 + 2) 返回一个"期望"的对象。 你通常不会对这些期望对象调用过多的匹配器。 在此代码中,.toBe(4) 是匹配器。 当 Jest 运行时,它会跟踪所有失败的匹配器,以便它可以为你打印出很好的错误消息。

在测试中,你有时需要区分 undefined、 null,和 false,但有时你又不需要区分。 Jest 让你明确你想要什么。

  • 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();
});

其他:

  数字:toBe() ,toEqual()

  字符串 :toMatch()

  数组:toContain()

  异常:toThrow()