loading...
Cover image for How to debug failing tests in jest

How to debug failing tests in jest

____marcell profile image Marcell Cruz Updated on ・2 min read

TL;DR

node inspect ./node_modules/jest/bin/jest.js --testRegex 'main.test.js' --runInBand
Enter fullscreen mode Exit fullscreen mode

Quick tip for debugging failing tests with jest
If you already know why would you want to run tests with the debugger you can skip the next paragraph

Why run a test with a debugger

If you run a test with the debugger you can use the debugger keyword inside your test or code to see what's happening and why the test is failing, if you don't know how to use the debugger you can read this article debugging node applicatoins

How to run a single test with the debugger

In order to debug a specific test you going to need to

  • run only the failing test
  • run the test in the same node process
  • run jest with the node debugger

So let's go over each step

Running only the failing test

To run only one test you going to need two things

  • run only one test file
  • use the keyword only to skip all other tests in that file

So let's say you have a test file called main.test.js, to run only that test file you need to run jest with the --testRegex option

jest --testRegex 'main.test.js'
Enter fullscreen mode Exit fullscreen mode

this going to match the test file main assuming that's no other file with main in the name
now that you are only running the tests in that file, you can use the keyword only in the test that you want to debug

// a lot of other tests above
...
test.only("this is the failing test :(", () => {
....
...
// a lot of other tests below
Enter fullscreen mode Exit fullscreen mode

Now when you run the command only one test is going to run

Run the test in the same process

Jest run tests in parallel to make the test suit faster, but this makes debugging impossible since the test could be running in another spawn process, in order to run the test with just one process you have to use the option --runInBand

jest --testRegex 'main.test.js' --runInBand
Enter fullscreen mode Exit fullscreen mode

Run jest with the node debugger

Now for the final part you just need to run jest with the debugger, since you can pass the debugger option after calling the program executable you going to need to find the executable installed in your process and run it manually with node, the good part is that it's always in the same place, assuming in are in the root folder of your project it should be in ./node_modules/jest/bin/jest.js
now the whole command

node inspect ./node_modules/jest/bin/jest.js --testRegex 'main.test.js' --runInBand
Enter fullscreen mode Exit fullscreen mode

and that's about it.

Discussion

pic
Editor guide