Debugging Mocha from Node using Chrome Inspector

How to debug Mocha tests running in Node using Chrome DevTools inspector.

If you are using Mocha test runner, you can easily debug the test execution using Node and Chrome DevTools inspector. I am using Mocha 3.5.3 and Node 8.9.4 in this demo.

1. Break at the start of the Node process

Here is my test command (I am working on detecting it.only used inside the tests, thus my command for this demo is only-test)

package.json
1
2
3
4
5
{
"scripts": {
"only-test": "mocha --inspect-brk only-test/test.js"
}
}

2. When starting the tests it pauses the execution and outputs the following message

1
2
3
4
5
6
7
8
$ npm run only-test

> [email protected] only-test /Users/gleb/git/snap-shot-it
> mocha --inspect-brk only-test/test.js

Debugger listening on ws://127.0.0.1:9229/40045c70-8525-4d12-a565-11066bc604a3
For help see https://nodejs.org/en/docs/inspector
Debugger attached.

3. Open in Chrome special url chrome://inspect which shows that there is a "remote target" available to connect.

Chrome inspect

If Chrome is already started, no problem, it will keep polling for remote devices and the Node process will appear once you start it.

4. The execution pauses at the start of the first loaded script, which in this case is _mocha

Break on start

If you want to pause at your code, add debugger statement

1
2
3
4
5
6
beforeEach(function () {
console.log('before each')
console.log(Object.keys(this))
debugger
// this._runnable.parent._onlyTests
})

5. Enjoy the full power of DevTools debugger while stepping through the unit tests!

Debugger statement