有多种方法可以为你的 Jest 测试设置调试器。我们将介绍 Chrome 和 Visual Studio Code 中的调试。
注意:调试测试需要 Node 8 或更高版本。
在 Chrome 中调试测试
将以下内容添加到项目的 package.json
中的 scripts
部分
"scripts": { "test:debug": "react-scripts --inspect-brk test --runInBand" }
在任何测试和运行中放置 debugger;
语句:
$ npm run test:debug
这将开始运行你的 Jest 测试,但在执行之前暂停以允许调试器附加到进程。
在 Chrome 地址栏中输入以下内容,回车:
about:inspect
打开该链接后,将显示 Chrome 开发者工具。选择 inspect
进程并在 react 脚本的第一行设置断点(这样做只是为了让你有时间打开开发人员工具并防止 Jest 在你有时间之前执行)。单击屏幕右上角看起来像 “play” 按钮的按钮以继续执行。当 Jest 执行包含调试器语句的测试时,执行将暂停,你可以检查当前范围和调用堆栈。
注意:--runInBand cli 选项可确保 Jest 在同一进程中运行测试,而不是为单个测试生成进程。通常,Jest 会跨进程并行化测试运行,但很难同时调试多个进程。
在 Visual Studio Code 中调试测试
Visual Studio Code 支持调试 Jest 测试。
使用以下 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" ], "cwd": "${workspaceRoot}", "protocol": "inspector", "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" } ] }