目前若要執行測試的話,都要 npm run test 一次,在開發階段每次更新檔案都要執行一次重複的動作,有點不方便。 可以使用 Jest Watch Mode 偵測檔案變動,自動執行測試,不需每次都手動執行。只要在 jest command 後面加上 --watch flag。
在 package.josn 加上 "test:watch": "jest --watch" ,之後只要執行 npm run test:watch ,Jest 就會自動幫我們 watch 檔案更新,自動執行測試:
package.json
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
...
},
現在 npm run test:watch 看看:
Console Output
No tests found related to files changed since last commit.
Press `a` to run all tests, or run Jest with `--watchAll`.
Watch Usage
› Press a to run all tests.
› Press f to run only failed tests.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press q to quit watch mode.
› Press Enter to trigger a test run.
結果得到 "No test found related to files change since last commit." ,這句話代表 Jest 找不到在上一次 git commit 之後更新的檔案可測試。當專案越來越大的時候,測試所花費的時間也會變多,我們不需要每次更新部分檔案後,都要把所有測試跑過一輪。Jest 的 —watch flag 所做的是:自動幫我們尋找「自從上一次 commit 之後」更動過的檔案,只會跑這次更動範圍內相關的測試。
另外,在 Console Output 裡,Jest 提供了一系列 Watch Usage 資訊,例如:按下 a 執行所有測試;按下 q 結束 watch mode;按下 p 或 t 執行特定檔案或名稱的測試。
現在隨意更動一下檔案把 code 改壞,Jest 會自動跑這次更動相關的測試:
Console Output
...
› 1 snapshot failed.
PASS src/__tests__/calculator.js
PASS src/shared/__tests__/auto-scaling-text.js
Snapshot Summary
› 1 snapshot failed from 1 test suite. Inspect your code changes or press `u` to update them.
Test Suites: 1 failed, 2 passed, 3 total
Tests: 1 failed, 2 passed, 3 total
Snapshots: 1 failed, 1 total
Time: 3.012s
Ran all test suites related to changed files.
Watch Usage
› Press a to run all tests.
› Press f to run only failed tests.
› Press p to filter by a filename regex pattern.
› Press t to filter by a test name regex pattern.
› Press u to update failing snapshots.
› Press i to update failing snapshots interactively.
› Press q to quit watch mode.
› Press Enter to trigger a test run.
可以看到相關的測試有三個,其中一個 fail 了,依據 Watch Usage 提示,我們可以:按下 f 只跑 fail 的測試,方便我們專注在 fail 的測試上,幫助 debug;按下 u 更新 snapshots;假設這次更動的檔案影響到非常多 snapshots,在 console 裡會顯示一長串的 fail 資訊,一次要滾動超長篇幅的資訊非常不易閱讀,按下 i 的話,Jest 可以一次顯示一個 snapshot 訊息,讓我們針對個別 snapshot 訊息逐步處理。
Jest 在 watch mode 裡面提供非常明確的提示訊息,我們可以很快理解接下來有哪些使用方式,依據這些提示,我們可以非常有彈性地執行想進行的動作,增進測試開發效率,這也是 Jest 這個測試框架非常強大之處。
除了
npm run test之外,也可以使用npm test或npm t,這是 npm 提供的 short command,非常方便。但 npm 並沒有針對 test:watch 提供 short command,所以只能完整使用npm run test:watch。