Skip to main content

调试测试

有多种方法可以为 Jest 测试设置调试器。我们介绍了 Chrome 和 Visual Studio Code 中的调试。

¥There are various ways to setup a debugger for your Jest tests. We cover debugging in Chrome and Visual Studio Code.

在 Chrome 中调试测试

¥Debugging Tests in Chrome

将以下内容添加到项目的 package.json 中的 scripts 部分

¥Add the following to the scripts section in your project's package.json

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

在任何测试中放置 debugger; 语句并运行:

¥Place debugger; statements in any test and run:

$ npm run test:debug

这将开始运行你的 Jest 测试,但在执行之前暂停以允许调试器附加到进程。

¥This will start running your Jest tests, but pause before executing to allow a debugger to attach to the process.

在 Chrome 中打开以下内容

¥Open the following in Chrome

about:inspect

打开该链接后,将显示 Chrome 开发者工具。在你的进程上选择 inspect,将在 react 脚本的第一行设置一个断点(这样做是为了让你有时间打开开发者工具,并防止 Jest 在你有时间执行之前执行)。单击屏幕右上角看起来像 "play" 按钮的按钮以继续执行。当 Jest 执行包含调试器语句的测试时,执行将暂停,你可以检查当前作用域和调用堆栈。

¥After opening that link, the Chrome Developer Tools will be displayed. Select inspect on your process and a breakpoint will be set at the first line of the react script (this is done to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a "play" button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the debugger statement, execution will pause and you can examine the current scope and call stack.

注意:--runInBand cli 选项确保 Jest 在同一进程中运行测试,而不是为单个测试生成进程。通常 Jest 会跨进程并行测试运行,但很难同时调试多个进程。

¥Note: the --runInBand cli option makes sure Jest runs test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time.

在 Visual Studio Code 中调试测试

¥Debugging Tests in Visual Studio Code

Visual Studio Code 开箱即用地支持调试 Jest 测试。

¥Debugging Jest tests is supported out of the box for Visual Studio Code.

使用以下 launch.json 配置文件:

¥Use the following launch.json configuration file:

{
"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
}
]
}