【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()字符串

相關文章
相關標籤/搜索