Debugging Unit Tests — Setup and Inspect
You can debug JavaScript unit tests running in Node.js (like Jest or Mocha) by launching the test runner with inspection enabled. Use the following command to start tests and pause on the first line:
node --inspect-brk ./node_modules/.bin/jest --runInBand
The --inspect-brk
flag starts the V8 inspector and stops at the first line. Adding --runInBand
ensures tests run in a single process, which is essential for reliable debugging.
Attach Chrome DevTools to Node
Open Chrome and go to chrome://inspect
. Under “Remote Target,” click “Open dedicated DevTools for Node” and select the Node process listening on 9229
. A dedicated DevTools window will open, paused at the beginning.
Pause Execution with debugger;
Insert a debugger;
statement in your test code to pause execution at the desired point. For example:
After restarting your test script and reconnecting DevTools, execution will pause at the debugger;
line, allowing you to inspect the current state.
Inspect and Step Through with DevTools
In DevTools, the Sources panel lets you view and edit code. Use breakpoints and step controls (step over/into/out) to navigate execution. The Scope and Call Stack panels expose variable states and function chains, and you can execute expressions live in the Console.
Restart After Changes
After altering code or test files, restart the process using the same --inspect-brk
command and reconnect DevTools. Your debugger;
statements or breakpoints will trigger as before.
Why This Workflow Helps
- Use Chrome DevTools’ full capabilities—conditional breakpoints, live editing, and expression evaluation.
- Avoid console cluttering—focused stepping gives a precise view of execution.
--runInBand
prevents child processes, ensuring your DevTools session stays connected.
Summary
Launch your test runner with inspection enabled, attach Chrome’s dedicated DevTools for Node, insert debugger;
where you need to break, then step through and inspect your code in real time. This method is faster, more reliable, and more powerful than relying on console logs.
No comments:
Post a Comment