Debugging the Tests

Learn how to debug tests and code when our Jest tests start to fail.

Navigating the failing tests

What do we do when a test fails?

When a test fails, one of two things is happening:

  1. Our code is not doing what we think it’s doing.

  2. Our test is not testing what we think it’s testing.

As a general rule, fix the code, not the tests. Tests should not be written to pass. They should be written to test our assumptions of how our code works and should pass because our code meets our expectations. If tests fail, the code should be fixed to execute as expected.

However, sometimes tests need to be updated to reflect changes in the codebase. Although, it is best to write tests so that implementation details are not being tested to avoid needing to update them regularly. Usually, the first pass at writing a test isn’t quite right and requires some tweaking to get it across the finish line. In these instances, we need to debug our tests to see why they aren’t passing.

Using the debugger; statement

As in other Node environments, we have the debugger; statement at our disposal. If you are not familiar with this, you can read more about it here in the Node.js documentation. We can add debugger; at any point in our code to pause execution and inspect the values of different objects and variables present in the relevant block of code.

This tool also functions inside our Jest testing environment, meaning we can add this same line at any point in our tests to pause the execution of a test and inspect its values. After placing the debugger; statements strategically inside of a failing test, we must run the command below inside the test directory:

node --inspect-brk node_modules/.bin/jest --runInBand

This command starts a Node process running Jest. We can then connect to this process with the debugger of our choice, such as Chrome’s or VSCode’s debugging tools.

Debugging in Chrome

To debug using Chrome, perform the following steps:

  1. Navigate to chrome://inspect in your Chrome browser.

  2. Click the button that says “Open Dedicated DevTools for Node.”

Get hands-on with 1400+ tech skills courses.