Jest 單元測試入門
今天,我們要講的是 Jest 單元測試的入門知識。
為何要進行單元測試?
在學習 Jest 之前,我們需要回答一個問題:為何要進行單元測試?編寫單元測試可以給你帶來很多好處:
- 將測試自動化,無需每次都人工測試。
- 變更檢查,當代碼發生重構,可以及時發現,並做出相應的調整。
- 列舉測試用例,可以幫你了解所有的邊界情況。
- 當作文檔,如果你的測試描述足夠詳細,生成的測試報告甚至可以當作文檔。
- ……
總之,單元測試會讓你的生活更加美好。
使用 Jest 進行單元測試
編寫測試通常都會基於某個測試框架,在眾多測試框架中我選擇了 Jest,不僅因為我是個 React 開發者(React 與 Jest 都是 Facebook 出的),而且因為它確實簡單好用。讓我們開始編寫測試吧!
首先,安裝 Jest:
|
1
|
npm install --save-dev jest
|
然后,編寫一個待測試的文件,以Stack類為例:
Stack.js
function Stack() {
// 私有變量 items,用於記錄數組,對象不能直接操作
var items = [];
// 類方法 push,在數組末尾添加項,對象可以直接調用
this.push = function (element) {
items.push(element);
};
// 刪除並返回數組末尾的項
this.pop = function () {
return items.pop();
};
}
接下來,編寫一個測試文件 Stack.test.js:
Stack.test.js
// 導入 Stack
var Stack = require('./Stack');
test('Stack', function () {
// 實例化一個 stack 對象
var stack = new Stack();
stack.push(8);
// 期望 stack 最后一項是8
expect(stack.pop()).toBe(8);
});
然后,在 package.json 中添加:
"scripts": {
"test": "jest"
}
最后,打開命令行運行:
npm test
PASS Stack.test.js結果會在命令行中生成測試報告:
Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 0.386s Ran all test suites.
在上面的測試代碼中有個 expect().toBe() 來判斷結果是否是預期,這叫斷言。
什么是斷言?在程序設計中,斷言(assertion)是一種放在程序中的一階邏輯(如一個結果為真或是假的邏輯判斷式),目的是為了標示與驗證程序開發者預期的結果。除了expect().toBe()之外,其他常用的斷言包括:斷言簡介
expect().toEqual():判斷結果是否和預期等價。expect().toBeFalsy():判斷結果是否為假。expect().toBeTruthy():判斷結果是否為真。
普通匹配器
- toBe - toBe 使用 Object.is 來測試是否完全相等
- .not - 用來測試相反的用例
- .toEqual - 如果你想檢查某個對象的值,請改用 toEqual。
toBe
最簡單的測試值的方法是看是否精確匹配。
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
toEqual
如果你想檢查某個對象的值,請改用 toEqual。
test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});
.not
用來測試相反的用例
test('null', () => {
const n = null;
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
});
布爾值匹配器
- 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();
});
數字匹配器
- .toBeGreaterThan() - 大於
- .toBeGreaterThanOrEqual() 大於等於
- .toBeLessThan() - 小於
- .toBeLessThanOrEqual() - 小於等於
- .toBeCloseTo() - 浮點數比較
toBeGreaterThan、toBeGreaterThanOrEqual、toBeLessThan、toBeLessThanOrEqual
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 和 toEqual 對於數字來說是一樣的
expect(value).toBe(4);
expect(value).toEqual(4);
});
.toBeCloseTo()
對於比較浮點數的相等,應該使用 toBeCloseTo
test('兩個浮點數字相加', () => {
const value = 0.1 + 0.2; // 0.30000000000000004
expect(value).toBe(0.3); // 這句會報錯,因為 js 浮點數有舍入誤差
expect(value).toBeCloseTo(0.3); // 這句可以運行
});
字符串匹配器
- toMatch - 正則表達式的字符
- .toHaveLength(number) - 判斷一個有長度的對象的長度
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/);
});
.toHaveLength(number)
判斷一個有長度的對象的長度
expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);
數組匹配器
- .toContain(item) - 判斷數組是否包含特定子項
- .toContainEqual(item) - 判斷數組中是否包含一個特定對象
.toContain
判斷數組是否包含特定子項
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'beer',
];
test('購物清單(shopping list)里面有啤酒(beer)', () => {
expect(shoppingList).toContain('beer');
});
.toContainEqual(item)
可以判斷數組中是否包含一個特定對象,類似 toEqual 與 toContain 的結合
function myBeverages() {
return [
{delicious: true, sour: false},
{delicious: false, sour: true}
]
}
test('is delicious and not sour', () => {
const myBeverage = {delicious: true, sour: false};
expect(myBeverages()).toContainEqual(myBeverage);
});
