Wednesday, November 11, 2015

node: Easier debugging of nodeunit with node-inspector on Windows

I was exploring how to get insight into a piece of JS code running on NodeJS. All the things were there but for some reason the unit tests were not behaving correctly. To debug this using node-inspector seem to be the logical choice but I could not find an easy way avenue to get things started.

I would normally start my unit test pointing nodeunit to a directory using the windows command that becomes available after installing nodeunit via npm globally:

c:\> nodeunit /test

This would run through all the unit tests in the /test directory. I wanted a similar mechanism when I needed to run debugging. Googling things was not very helpful as all the examples I found were OSX or Linux specific. However, the solution in the end was fairly simple.

Here are the steps from the beginning:

a) install node-inspector globally

c:\> npm install -g node-inspector

b) install nodeunit globally

c:\> npm install -g nodeunit

c) locate the nodeunit command file normally somewhere like C:\Users\[logged in user]\AppData\Roaming\npm\nodeunit.cmd. Or you can use the "where" command like so:

c:\> where nodeunit

d) use a text editor like notepad to open the command file

e) change the nodeunit command file by adding the debug flags (--debug-brk) and save as nodeunit-debug.cmd. Here is the content of the fully changed command file:

@IF EXIST "%~dp0\node.exe" (
  "%~dp0\node.exe" "--debug-brk %~dp0\node_modules\nodeunit\bin\nodeunit" %*
) ELSE (
  node --debug-brk "%~dp0\node_modules\nodeunit\bin\nodeunit" %*

You are done with your setup config. Thereafter you only need to use the new debug command when you want to debug test cases.

a) run your tests with new nodeunit-debug command you just created. You should, of course, do so in the directory of your application rather than in the root of the drive. Assuming that all your unit tests are under a /test subdirectory you could do it like so:

c:\[app dir]> nodeunit-debug /test

b) in second command window run node inspector instance and inspect code in browser (Chrome)

c:\> node-inspector

c) open chrome to debug your code (

Here is an image of a,b, and c steps in action:

That is it.