173

I can't find any information on debugging my unit tests written with Jest.

How do you debug Jest Tests ?

2
  • 10
    I know this is post is aged. However, I wanted to add an update that might be helpful. There now exists a VSC extension simply called Jest. It adds real-time feedback when working in .test.js files. Hope this helps. Commented Nov 13, 2019 at 16:35
  • @MikeS. good information, my man! 💯 Commented Apr 3, 2024 at 13:28

15 Answers 15

331

You do not need Chrome for Jest tests.

The simplest solution I found is to use VS Code JavaScript Debug Terminal.

And it works with Typescript and Nrvl.Nx work-spaces out of the box.

  1. Open the command palette and start Debug: JavaScript Debug Terminal:

enter image description here

  1. Run tests in that terminal in a Watch mode npm test -- --watch. (or yarn test --watch if you are using yarn)
  2. Set a break-point in your file.
  3. Make any change in a file you want to debug and save.
  4. watch will run Jest tests against modified files.

When you want to narrow down the number of files run by the --watch, press p in the terminal and enter a pattern, which is just a part of the file name you want to test and hit [Enter]

To limit it to a single test in a file - focus it with f, so change it(...) to fit(...)

Sign up to request clarification or add additional context in comments.

7 Comments

perfect..this should be the answer
I had to use npm test -- --watch but otherwise perfect answer!
thrown: "Exceeded timeout of 5000 ms for a test. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
Like @PirateApp mentioned, Jest has a max. default timeout so tests should run within 5s, but we need more than that to debug. We can change this max. timeout on jest.setup.js, but wondering if there's better alternative?
@PirateApp I never had a problem with timeout, so it could be something specific to your settings.
|
48

You can use Chrome DevTools to debug Jest tests.

First, start Node debugger in your project:

node --inspect-brk <path to jest.js> --runInBand <path to your test file>

Examples:

  • If you install Jest locally (Linux example):

    node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand mymodule/test.js

  • If you install Jest globally (Windows example):

    node --inspect-brk "C:\\Program Files\\nodejs\\node_modules\\jest\\bin\\jest.js" --runInBand mymodule\\test.js

Then, you can open the Google Chrome browser, and type in the address bar:

chrome://inspect

Now click the inspect link under "Remote Target" to open Chrome DevTools.

Note that you probably need to add the source code folder to the workspace in chrome-devtools, so as to be able to set breakpoints.

Now you can press F8 to start debugging.

[FYI]:

  • My Node version: v10.11.0
  • My Jest version: 23.6.0
  • My Google Chrome version: 71.0.3578.98

[Update] Regarding the step of adding the source code folder to the workspace in chrome-devtools (as asked by Sam), it looks like below:

enter image description here

And then you can open your script files and set the breakpoints:

enter image description here

You find the simple demo project on my GitHub repo.

3 Comments

Hi @Yuci, can you explain how to add the source code folder to the workspace in chrome-devtools?
@SamKahChiin, see my update on adding the source code folder to the workspace in chrome-devtools
This is the best answer because it is agnostic to the text editor being used. This works on any chromium based web browser, and if you are developing web apps then it would expect me that you have one installed.
18

As of 2021, check Debugging in VS Code from Jest docs. Add the configurations below to your .vscode/launch.json file.

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Jest Tests",
      "type": "node",
      "request": "launch",
      "runtimeArgs": [
        "--inspect-brk",
        "${workspaceRoot}/node_modules/jest/bin/jest.js",
        "--runInBand"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "port": 9229
    }
  ]
}

1 Comment

Still, working in 2023 with jest version 29.5
14

I wrote a blog post on 7 ways to debug Jest tests in terminal. Here's the fastest way to do it from it.

You can install ndb, an improved debugging experience for Node.js, enabled by Chrome DevTools, with

npm install -g ndb

Then you can run:

ndb npm run test

which will open the DevTools for you and run the tests.

Or you can just put in one command with:

npx ndb npm run test

and you're good to go. But do check out the blog post where I go into details of different ways to debug Jest tests.

Comments

11

This is my basic config for debugging Jest in VSCode, add to your launch configurations within settings.json

"launch" : {
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Jest",
      "program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
      "args": [
          "-i"
      ],
       "skipFiles": [
        "<node_internals>/**/*.js", "node_modules",
      ]
    }
  ],
},

Comments

5

Here's a one-liner you can add to your projects to use debugger; in your Jest test files:

  1. add this script to package.json:
  "test:debug": "open -a \"Google Chrome\" chrome://inspect && node --nolazy --inspect-brk ./node_modules/jest/bin/jest.js --runInBand --colors --verbose",
  1. run the script within your project:
yarn test:debug insert/path/to/file
  1. Now you can use debugger; within your test files to trigger line-of-code breakpoints in Google Chrome! 🐛 🔫

The script has two parts. First, it opens Chrome — to: chrome://inspect — and then it will start a Node process (where we can use debugger) that runs a jest file (from node modules) on a specific test file. As a result, you must have Jest installed in your project dependencies!

Comments

2

@Yuci answer was perfect for me.

I'm just precising it in case of you're using jest inside local Docker container. You need to precise --inspect-brk=0.0.0.0:9229

node --inspect-brk=0.0.0.0:9229 <path to jest.js> --runInBand <path to your test file>

1 Comment

This is a useful answer in that it covers docker and various other remote scenarios but using it haphazardly is a potential security hole. See nodejs.org/en/docs/guides/debugging-getting-started/… for alternatives.
1

Run

node --debug-brk node_modules/.bin/jest

in your project directory. It should start the node process paused an listening (usually at port 5858) for a debugger. Visual Studio Code is an example of a nice graphical debugger for node.js that can be used to connect to the listening node process.

Comments

1

Adding jest configuration would work only if there is only one project. However, if there are multiple projects within its own folder (i.e. rootfolder/project1, rootfolder/project2), running "jest --watchAll --runInBand --coverage" with breakpoint either in the test file or the file under test would be good option

Comments

1

If you're rendering content with a frontend library like react-testing-library, you probably need a visual feedback of your test to debug it.

While Jest uses a virtual DOM, jest-preview adds a browser rendering, so you can actually see what your test is doing.

import { render } from '@testing-library/react';
import { debug } from 'jest-preview';

describe('App', () => {
  it('should work as expected', () => {
    render(<App />);
    debug();
  });
});

And if you're using Vitest, the equivalent library is called vitest-preview

1 Comment

Vitest has an official browser mode environment baked into it which executes your code browser-side and gives you a full preview of your rendered output.
1

for some cases it might be enough to gather debug logs.
it's possible to activate them with environment variables as explained in the doc

Linux/MacOS: export TS_JEST_LOG=ts-jest.log

Windows: set TS_JEST_LOG=ts-jest.log

Comments

0

For anyone seeking an answer, you debug jest with node-inspector. However this is a very slow process (2-5 minutes to debug a single test), and wasn't very useful in actual usage.

I haven't found a better way to debug Jest, however I have seen a lot of people doing the extra work to make jasmine or mocha work with react components. So that may be a more viable option until node-inspector is actually usable.

Comments

0

The following worked for me:

  1. We set breakpoints in the test and the code under test if necessary
  2. Right-click on the icon next to the name of the test in the test file. In the menu that opens, click on Debug Test. enter image description here

3. After that, the interpreter will start stopping at the places where you have set breakpoints. Good luck to everyone

Comments

0

Use VS Code built-in debugger. The .vscode/launch.json(windows):

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Jest Tests",
      "type": "node",
      "request": "launch",
      "runtimeArgs": [
        "--inspect-brk",
        "${workspaceRoot}/node_modules/jest/bin/jest.js",
        "--runTestsByPath"
      ],
      "program": "${file}",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen"
    }
  ]
}

More often, you probably want to debug a single test file. Combine program: ${file} and jest CLI --runTestsByPath option will do it.

Run only the tests that were specified with their exact paths. This avoids converting them into a regular expression and matching it against every single file.

The ${file} means the file open in the active editor.

For example, I want to debug the test-component.test.tsx file, active the file tab in the VS Code Editor, then Press F5.

enter image description here

Comments

0

The better solution is to install debugging extension in your VS code. Once installed you should be able to run debugger from within your unit tests by clicking the debug button. See the following video for details on how to run the debugger.

https://www.youtube.com/watch?v=uUWXDFGOkNA

  • Open the extensions panel (Ctrl + Shift + X)
  • Search for extension jest with most downloads and install it
  • Once installed, restart your VS
  • Setup breakpoints in your code that needs debugged
  • In your test file above each it('..' or description('.. statement you will see the debug button, click the one that needs testing

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.