學習Jest——語法篇

使用匹配器

使用不同匹配器可以測試輸入輸出的值是否符合預期。下面介紹一些常見的匹配器。

普通匹配器

最簡單的測試值的方法就是看是否精確匹配。首先是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。以下的一些規則有助于我們進行。

  • toBeNull只匹配null
  • toBeUndefined只匹配undefined
  • toBeDefine與toBeUndefined相反
  • toBeTruthy匹配任何if語句為真
  • toBeFalsy匹配任何if語句為假

數字匹配器
大多數的比較數字有等價的匹配器。

  • 大于。toBeGreaterThan()
  • 大于或者等于。toBeGreaterThanOrEqual()
  • 小于。toBeLessThan()
  • 小于或等于。toBeLessThanOrEqual()
  • toBe和toEqual同樣適用于數字
    注意:對比兩個浮點數是否相等的時候,使用toBeCloseTo而不是toEqual

例子如下:

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);
});
test('兩個浮點數字相加', () => {
  const value = 0.1 + 0.2;
  //expect(value).toBe(0.3);           這句會報錯,因為浮點數有舍入誤差
  expect(value).toBeCloseTo(0.3); // 這句可以運行
});

如果使用toBe就會產生以下結果:

錯誤

字符串
使用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)里面有啤酒(beer)', () => {
  expect(shoppingList).toContain('beer');
});

另外
如果你想在測試特定函數的時候拋出一個錯誤,在它調用的時候可以使用toThrow。

function compileAndroidCode() {
  throw new ConfigError('you are using the wrong JDK');
}

test('compiling android goes as expected', () => {
  expect(compileAndroidCode).toThrow();
  expect(compileAndroidCode).toThrow(ConfigError);

  // You can also use the exact error message or a regexp
  expect(compileAndroidCode).toThrow('you are using the wrong JDK');
  expect(compileAndroidCode).toThrow(/JDK/);
});

測試異步代碼

在實際開發過程中,我們經常會遇到一些異步的JavaScript代碼。當你有以異步方式運行的代碼的時候,Jest需要知道當前它測試的代碼是否已經完成,然后它可以轉移動另一個測試。也就是說,測試用例一定要在測試對象結束之后才能夠結束

為了達到這一目的,Jest有多種方法可以做到。
回調
最常見的異步模式就是回調函數。

注意:回調函數和異步沒有必然的聯系,回調只是異步的一種調用方式而已,不要將異步和回調兩個概念結合起來談

比如以下代碼:

// 這里是同步執行的,完全沒有異步
function fun1(callback) {
  callback();
}

現在假設一個fetchData(call)函數,獲取一些數據并在完成的時候調用call(data),而我想要測試返回的數據是不是字符串'peanut butter'

默認情況下,一旦到達運行上下文底部,jest測試就會立即結束。這意味著這個測試將不能按照預期的進行。

function fetchData(call) {
  setTimeout(() => {
    call('peanut butter1')
  },1000);
}

test('the data is peanut butter', () => {
  function callback(data) {
    expect(data).toBe('peanut butter'); // 這里沒有執行到
    // done()
  }
  fetchData(callback);
});

這樣做是不會報錯的,因為沒有執行到我們想要測試的語句中的時候Jest測試已經結束了。(一旦fetchData執行結束,此測試就在沒有調用回調函數前結束,因為使用了setTimeout,產生了異步)

而我們可以改成以下:
使用單個參數調用done,而不是將測試放在一個空參數的函數中,Jest會等done回調函數執行結束后,結束測試。

function fetchData(call) {
  setTimeout(() => {
    call('peanut butter1')
  },1000);
}

test('the data is peanut butter', (done) => {
  function callback(data) {
    expect(data).toBe('peanut butter');
    done()
  }
  fetchData(callback);
});
可行

如果done()永遠不會被調用,則說明這個測試將失敗,這也正是我們所希望看到的。

Promise
如果我們的代碼中使用到了Promises,只需要從你的測試中返回一個Promise,Jest就會等待這個Promise來解決。如果承諾被拒絕,則測試將會自動失敗。

舉個例子,如果fetchData,使用Promise代替回調的話,返回值是應該解析為一個字符串'peanut butter'的Promise。那么我們可以使用以下方式進行測試代碼:

test('the data is peanut butter', () => {
  expect.assertions(1);
  return fetchData().then(data => {
    expect(data).toBe('peanut butter');
  });
});

注意:一定要返回Promise,如果省略了return語句,測試將會在fetchData完成之前完成。

另外一種情況,就是想要Promise被拒絕,我們可以使用.catch方法。另外,要確保添加了expect.assertions來驗證一定數量的斷言被調用。否則一個fulfilled態的Promise不會讓測試失敗。

test('the fetch fails with an error', () => {
  expect.assertions(1);
  return fetchData().catch(e => expect(e).toMatch('error'));
});

.resolves/.rejects
可以使用./resolves匹配器匹配你的期望的聲明(跟Promise類似),如果想要被拒絕,可以使用.rejects

test('the data is peanut butter', () => {
  expect.assertions(1);
  return expect(fetchData()).resolves.toBe('peanut butter');
});
test('the fetch fails with an error', () => {
  expect.assertions(1);
  return expect(fetchData()).rejects.toMatch('error');
});

Async/Await
若要編寫async測試,只要在函數前面使用async關鍵字傳遞到test。比如,可以用來測試相同的fetchData()方案

test('the data is peanut butter', async () => {
  expect.assertions(1);
  const data = await fetchData();
  expect(data).toBe('peanut butter');
});

test('the fetch fails with an error', async () => {
  expect.assertions(1);
  try {
    await fetchData();
  } catch (e) {
    expect(e).toMatch('error');
  }
});

setup and teardown

寫測試的時候,我們經常需要進行測試之前做一些準備工作,和在進行測試后需要進行一些整理工作。Jest提供輔助函數來處理這個問題。

為多次測試重復設置
如果你有一些要為多次測試重復設置的工作,可以使用beforeEach和afterEach。

有這樣一個需求,需要我們在每個測試之前調用方法initializeCityDatabase(),在每個測試后,調用方法clearCityDatabase()

beforeEach(() => {
  initializeCityDatabase();
});

afterEach(() => {
  clearCityDatabase();
});

test('city database has Vienna', () => {
  expect(isCity('Vienna')).toBeTruthy();
});

test('city database has San Juan', () => {
  expect(isCity('San Juan')).toBeTruthy();
});

一次性設置
在某些情況下,你只需要在文件的開頭做一次設置。這種設置是異步行為的時候,你不太可能一行處理它。Jest提供了beforeAll和afterAll處理這種情況。

beforeAll(() => {
  return initializeCityDatabase();
});

afterAll(() => {
  return clearCityDatabase();
});

test('city database has Vienna', () => {
  expect(isCity('Vienna')).toBeTruthy();
});

test('city database has San Juan', () => {
  expect(isCity('San Juan')).toBeTruthy();
});

作用域
默認情況下,before和after的塊可以應用到文件中的每一個測試。此外可以通過describe塊來將將測試中的某一塊進行分組。當before和after的塊在describe塊內部的時候,則只適用于該describe塊內的測試。

比如說,我們不僅有一個城市的數據庫,還有一個食品數據庫。我們可以為不同的測試做不同的設置︰

// Applies to all tests in this file
beforeEach(() => {
  return initializeCityDatabase();
});

test('city database has Vienna', () => {
  expect(isCity('Vienna')).toBeTruthy();
});

test('city database has San Juan', () => {
  expect(isCity('San Juan')).toBeTruthy();
});

describe('matching cities to foods', () => {
  // Applies only to tests in this describe block
  beforeEach(() => {
    return initializeFoodDatabase();
  });

  test('Vienna <3 sausage', () => {
    expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true);
  });

  test('San Juan <3 plantains', () => {
    expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true);
  });
});

注意:頂級的beforeEach描述塊內的beforeEach之前執行,以下的例子可以方便我們認識到執行的順序

beforeAll(() => console.log('1 - beforeAll'));
afterAll(() => console.log('1 - afterAll'));
beforeEach(() => console.log('1 - beforeEach'));
afterEach(() => console.log('1 - afterEach'));
test('', () => console.log('1 - test'));
describe('Scoped / Nested block', () => {
  beforeAll(() => console.log('2 - beforeAll'));
  afterAll(() => console.log('2 - afterAll'));
  beforeEach(() => console.log('2 - beforeEach'));
  afterEach(() => console.log('2 - afterEach'));
  test('', () => console.log('2 - test'));
});

// 1 - beforeAll
// 1 - beforeEach
// 1 - test
// 1 - afterEach
// 2 - beforeAll
// 1 - beforeEach  //特別注意
// 2 - beforeEach
// 2 - test
// 2 - afterEach
// 1 - afterEach
// 2 - afterAll
// 1 - afterAll
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • JavaScript中經常有異步運行的代碼。如果你要測試異步的代碼,Jest需要知道他測試的代碼是否已經完成異步動...
    人頭原子彈閱讀 5,699評論 0 0
  • 你不知道JS:異步 第三章:Promises 接上篇3-1 錯誤處理(Error Handling) 在異步編程中...
    purple_force閱讀 1,416評論 0 2
  • 特別說明,為便于查閱,文章轉自https://github.com/getify/You-Dont-Know-JS...
    殺破狼real閱讀 660評論 0 3
  • 今日總結:今天的狀態比云天稍微差了些,主要是,5:00到6:00之間一直被拒絕,有點受挫,不過還好很快調整...
    迷失第二季閱讀 374評論 0 1
  • 緣分???無緣無分,有緣無分,無緣有分,有緣有分,一切皆有可能,一切也皆不可能! 緣分一觸即發,說來就來;緣分稍縱...
    迷霧凡塵閱讀 322評論 0 0