乐闻世界logo
搜索文章和话题

How to run and debug tests in Jest? What are the common command line options?

2月21日 15:54

Jest provides multiple methods for running and debugging tests:

Running Tests:

bash
# Run all tests jest # Run specific file jest path/to/test.spec.js # Run tests matching pattern jest --testNamePattern="should add" # Watch mode (auto-run on file changes) jest --watch # Run only failed tests jest --onlyFailures # Run tests related to changed files jest --onlyChanged

Debugging Tests:

1. Using console.log:

javascript
test('debug example', () => { const result = calculate(2, 3); console.log('Result:', result); expect(result).toBe(5); });

2. Using --verbose option:

bash
jest --verbose

3. Using --no-coverage to disable coverage:

bash
jest --no-coverage

4. Setting breakpoints in tests:

javascript
test('debug with debugger', () => { debugger; // Set breakpoint in browser or IDE const result = calculate(2, 3); expect(result).toBe(5); });

5. Using Jest debug mode:

bash
# Node.js debugging node --inspect-brk node_modules/.bin/jest --runInBand # VSCode debug configuration { "type": "node", "request": "launch", "name": "Jest Current File", "program": "${workspaceFolder}/node_modules/.bin/jest", "args": ["${fileBasenameNoExtension}", "--runInBand"], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen" }

Common Options:

  • --runInBand: Run tests sequentially (for debugging)
  • --detectOpenHandles: Detect unclosed handles
  • --forceExit: Force exit
  • --bail: Stop after first test failure
标签:Jest