【Jest】笔记二:Matchers匹配器

1、前言

  什么是匹配器?javascript

  咱们能够把匹配器当作,testng断言,这么理解就能够了java

 

2、经常使用的匹配器

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 语句为假

例如:code

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()blog

  数组:toContain()ip

  异常:toThrow()字符串

相关文章
相关标签/搜索