這陣子,經手的專案越來越多。 每隔一段時間去 review 自己當初寫的 code。經常覺得我到底是看了什麼。 這時就會很後悔當初一開始的時候,沒有好好的用 Jest 或 Typescript 提升自己得編碼品質。
這邊簡單記錄一下一下 Jest 的基礎用法。其實也都是當時看官方文件做的筆記。
npm init
把資料輸入後,安裝 Jest (我自己是用 yarn) 到開發 Dependencies
使用 yarn
yarn add jest -D
使用 npm
npm install jest -D
接下來修改 package.json , scripts 裡面的 test 的值,改成 jest
{ "scripts": { "test": "jest" } }
啟動的指令如下:
yarn
yarn test
npm
npm run test
執行後, jest 就會去尋找所有 .test.js 或是 test.ts 的檔案進行測試。
假設我們一個要測試專案目錄下的檔案 math.js
// math.js function sum(a, b) { return a + b } function subtract(a, b) { return a - b } module.exports = { sum, subtract }
我們要它建立一個測試檔案 math.test.js,基本用法如下:
// math.test.js // 把要測試的 function 引入 const { sum, subtract } = require("../math") // 這時 test 已經是一個全域指令 test('test is function', () => { expect(sum(1, 3)).toBe(4) })
test 這個 function 有兩個參數。
- 第一個參數是測試名稱,基本上可以自己命名。
- 第二個則是測試用的函式,函式內的 expect 用來描述測試的內容,可以包含很多個內容。
expect 函數則是提供了多種不同的方法來進行測試的判斷。
expect 的第一個參數帶入要測試的值,後面的 .toBe(4) ,表示這個值必須等於 4。
也可以寫很多個判斷,中間有錯誤就會中斷,並告知測試 fail:
// math.test.js test('my first test is sum function', () => { expect(sum(1, 3)).toBe(4) expect(sum(1, 3)).toBe(3) })
只要執行 yarn test 或是 npm run test ,就可以得到測試的結果:
常用的測試邏輯如下:
- .toBe(value) : 等於 value,如果 value 是 object 時,value 和 except 的值必須是同一個儲存空間
- .toEqual(value) : 等於 value,如果 value 是 object 時,會去比較每一個 property 的值
- toBeCloseTo(value) : 小數點計算時, js 會產生浮點數,用這個方法捨棄誤差
- .not.toBe(value) : 不等於 value,所有前面加 not 都是反向
- .toBeNull() : 等於 null
- .toBeLessThan(value) : 比 value 小
- .toBeGreaterThan(value) : 比 value 大
- .toBeLessThanOrEqual(value) : 小於等於 value
- .toBeGreaterThanOrEqual(value) : 大於等於 value
- .toBeTruthy() : === true
- .toBeFalsy() : === false
- .toContain(value) : 如果期望是陣列時,必須包含 value
- .toMatch(/p/g) : 使用標準表達式驗證
基礎的用法大概就是這樣。有空再繼續補充。