跳到主要內容

除錯測試

有許多方法可以為 Jest 測試設定偵錯器。我們將介紹如何在 Chrome 和 Visual Studio Code 中除錯。

在 Chrome 中除錯測試

將以下內容新增至專案 package.json 中的 scripts 區段

"scripts": {
"test:debug": "react-scripts --inspect-brk test --runInBand --no-cache"
}

在測試中放置 debugger; 語句並執行

$ npm run test:debug

這將開始執行 Jest 測試,但在執行前會暫停,讓偵錯器可以附加到處理程序。

在 Chrome 中開啟以下內容

about:inspect

開啟連結後,將顯示 Chrome 開發者工具。選擇你的處理程序上的 檢查,並在 React 腳本的第一個欄位設定斷點(這是為了讓你時間打開開發者工具,並防止在你有時間之前 Jest 就執行)。按一下螢幕右上角看起來像「播放」按鈕的按鈕,繼續執行。當 Jest 執行包含偵錯器語句的測試時,執行將暫停,你可以檢查目前的作用範圍和呼叫堆疊。

注意: --runInBand CLI 選項確保 Jest 會在同一個處理程序中執行測試,而不是為單一測試產生處理程序。通常,Jest 會在處理程序間並行測試執行,但是很難同時除錯多個處理程序。

Visual Studio Code 中的偵錯測試

偵錯 Jest 測試在 Visual Studio Code 中開箱即用。

使用下列 launch.json 組態檔

{
"version": "0.2.0",
"configurations": [
{
"name": "Debug CRA Tests",
"type": "node",
"request": "launch",
"runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts",
"args": ["test", "--runInBand", "--no-cache", "--watchAll=false"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"env": { "CI": "true" },
"disableOptimisticBPs": true
}
]
}