當寫好一個功能的時候,也許會做不同的資料上的手動測試,看程式會不會爆掉。
而通常就是把結果用console.log()給印下來

1
2
3
4
5
6
7
8
9
10
function repeat(str, times) {
let result = "";
for (let i = 0; i < times; i++) {
result += str;
}
return result;
}
console.log(repeat("cat", 3)); //catcatcat
console.log(repeat("dog", 2)); //dogdog
}

當專案越來越龐大,這樣的手動測試會越來越不容易


Jest 可以幫助我們寫一個測試的檔案

Jest 官方文件

根據文件上的教學

  • 首先透過npm install --save-dev jest 安裝套件
1
npm install --save-dev jest
  • package.json檔案下的scripts新增一個test的快捷指令,要執行的指令為”jest”
1
2
3
4
5
{
"scripts": {
"test": "jest"
}
}

執行 Jest 的時候 , Jest 會去找尋主程式檔名後綴.test的檔案
例如主程式檔名為repeat.js,就會去找尋repeat.test.js的檔案當測試檔

再來一次範例

1
2
3
4
5
6
7
8
9
10
//重複某段字串數次
function repeat(str, times) {
let result = "";
for (let i = 0; i < times; i++) {
result += str;
}
return result;
}

module.exports = repeat; //把功能導出
1
2
3
4
5
6
7
8
9
10
11
const repeat = require("./repeat");

describe("test repeat", () => {
test("a repeat 3 times", () => {
expect(repeat("a", 3)).toBe("aaa");
});

test("b repeat 1 times", () => {
expect(repeat("b", 1)).toBe("b");
});
});

整個測試集合的描述為test repeat

第一個test(測試)的expecta重複三次,toBe(期望值)為aaa
對這個單元測試的描述為a repeat 3 times

第一個test(測試)的expectb重複一次,toBe(期望值)為b
對這個單元測試的描述為b repeat 1 times


  • describe : 創建一個將幾個相關測試組合在一起的模塊
  • test : 運行測試的方法
  • expect : 判斷是否和預期值相同
  • toBe : 期望的結果

接著在終端機執行npm run test

就會跟你說這次的單元測試有沒有過,有個話就會跟你說Ran all test suites.

接下來來一個測試出錯的範例

for迴圈變成了<=,代表功能沒寫好,會多執行一次

1
2
3
4
5
6
7
8
9
function repeat(str, times) {
let result = "";
for (let i = 0; i <= times; i++) {
result += str;
}
return result;
}

module.exports = repeat;

測試不變

1
2
3
4
5
6
7
const repeat = require("./repeat");

describe("repeat", () => {
test("a repeat 3 times", () => {
expect(repeat("a", 3)).toBe("aaa");
});
});

Jest 就會顯示期望的數值是aaa,但得到的數值卻是aaaa

1
2
Expected: "aaa"
Received: "aaaa"

 以上就是這篇的筆記內容

程式導師實驗計畫第三期