In Ruby tests, I frequently find myself stepping into a REPL when something doesn’t behave as expected. Naturally I wanted to do the same with Jest.

With pry or similar, this is as simple as:

debugger

When starting out with testing React components, I quickly found I missed this functionality, so here’s how I tackled it.

In your package.json file, you will probably have something like:

//...
"scripts": {
  "test": "node ./node_modules/jest-cli/bin.jest"
}

which points npm test at the Jest binary. We can run the same binary with node debug:

node debug ./node_modules/jest-cli/bin/jest.js

But you will likely encounter issues with jest’s use of harmonize, so you’ll need this flag:

node debug --harmony ./node_modules/jest-cli/bin/jest.js

Another gotcha - Jest runs tests in parallel, so for ease of debugging you will want to pass it the -runInBand flag:

node debug --harmony ./node_modules/jest-cli/bin/jest.js --runInBand

Awesome! This setup should allow you to add debugger; to your javascript files as you might with Pry.

Now, back to package.json! We could probably setup an alias for this in .bashrc, but it would certainly be neater to add it as an npm script!

//...
"scripts": {
  //...
  "testdbg": "node debug --harmony ./node_modules/jest-cli/bin/jest.js"
}

NPM defines the test command that runs the script of the same name defined in package.json, however any other scripts should be run with:

npm run scriptname

So this script can be run with:

npm run testdbg

or, if you wish to specify a specific test file:

npm run testdbg -- TestFile.js

If you’re coming from Pry and the like, you’ll find node debug works as you’d expect, with c and s providing continue and step functionality, however if you need an interactive prompt in the current context, you must enter repl.

Happy debugging!