Jest 提供了多种运行测试和调试测试的方法:
运行测试:
bash# 运行所有测试 jest # 运行特定文件 jest path/to/test.spec.js # 运行匹配模式的测试 jest --testNamePattern="should add" # 监听模式(文件变化时自动运行) jest --watch # 只运行失败的测试 jest --onlyFailures # 运行修改过的文件相关测试 jest --onlyChanged
调试测试:
1. 使用 console.log:
javascripttest('debug example', () => { const result = calculate(2, 3); console.log('Result:', result); expect(result).toBe(5); });
2. 使用 --verbose 选项:
bashjest --verbose
3. 使用 --no-coverage 禁用覆盖率:
bashjest --no-coverage
4. 在测试中设置断点:
javascripttest('debug with debugger', () => { debugger; // 在浏览器或 IDE 中设置断点 const result = calculate(2, 3); expect(result).toBe(5); });
5. 使用 Jest 的调试模式:
bash# Node.js 调试 node --inspect-brk node_modules/.bin/jest --runInBand # VSCode 调试配置 { "type": "node", "request": "launch", "name": "Jest Current File", "program": "${workspaceFolder}/node_modules/.bin/jest", "args": ["${fileBasenameNoExtension}", "--runInBand"], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" }
常用选项:
--runInBand:顺序运行测试(用于调试)--detectOpenHandles:检测未关闭的句柄--forceExit:强制退出--bail:第一个测试失败后停止