PASS ./main.test.js
√ a + b = 5 (7 ms)
√ a + b = 10 (1 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 2.877 s
Ran all test suites.
若我們將第一個 test 函式中的 toBe(5) 改為 toBe(6)並重新執行測試:
FAIL ./main.test.js
× a + b = 5 (7 ms)
√ a + b = 10
● a + b = 5
expect(received).toBe(expected) // Object.is equality
Expected: 6
Received: 5
2 |
3 | test('a + b = 5', () => {
> 4 | expect(add(3, 2)).toBe(6);
| ^
5 | });
6 |
7 | test('a + b = 10', () => {
at Object.test (main.test.js:4:23)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 6.758 s
scripts: { "test": "jest" }
//...略
expect()
的參數為要測試的值或函式;toBe()
為一個 matcher,參數為expect()
測試的期望值。'two plus two is four'
用來描述此測試的功能(二加二等於四);expect(2 + 2)
的 2 + 2 為要測試的內容;toBe(4)
的 4 為 2 + 2 的期望值。示範
在專案資料夾底下,有一個
main.js
檔案,我在裡面寫了一個簡單的加法函式:我想用 Jest 測試 add 函式,先將它 export 出去:
module.exports = add
在終端機輸入
npm run test
方可進行自動化測試,以下為測試結果:若我們將第一個 test 函式中的
toBe(5)
改為toBe(6)
並重新執行測試:會顯示 fail,並指出測試結果應為 5 而不是 6。
更多常用的 matchers
編寫測試時需要讓值符合期望,Jest 中的 expect 後方可以使用
matchers
(匹配器)作為條件驗證,如先前的範例expect(...).toBe(...)
中的toBe()
就屬於 matchers,作為各種不同條件的驗證使用。測試是否為
null
、true
、false
、或者undefined
:toBeNull
:matches only nulltoBeUndefined
: matches only undefinedtoBeTruthy
:matches anything that anif
statement treats as truetoBeFalsy
:matches anything that anif
statement treats as false物件對比:
這邊得到 false 的結果與變數儲存模型有關,詳情可複習 從 Object 的等號真正的理解變數(變數儲存模型)。 在 Jest 也是相同概念,如若直接使用
toBe()
來比對物件一樣會得到 fail 的結果。 若單純想對比物件內的值則可使用toEqual()
,範例:數值比對
toMactch
字串包含使用
toMatch()
測試一個字串有無包含特定字串:測試會 fail,因為字串
'team'
沒有包含 大寫I
,或也可使用正規表達式:測試會通過,因為字串
Christoph
有包含stop
。toContain
判斷一個陣列是否含有某值describe
describe
的用途是提供一個群組的描述,將多個 test 包在一起,讓程式看起來更有結構性