Jest: debugger; and breakpoints don't work with node --inspect

Created on 9 Sep 2016  ·  77Comments  ·  Source: facebook/jest

Currently breakpoints can be set for use with node debug using the keyword debugger;, but any breakpoints set with debugger; when using node --inspect are ignored. This only applies to the test code; breakpoints set with debugger; within Jest or other node_module libraries are honored.

I set up a test repository to demonstrate the difference: https://github.com/snapwich/jest-inspect. Both methods can be tested by pulling the repo and running the following:

npm install

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

// doesn't honor "debugger;"
node --inspect --debug-brk ./node_modules/.bin/jest -i

Also, after the initial run-through with node --inspect, breakpoints can be applied to the code in the Sources tab. Any breakpoints placed in test code (such as __tests__/jest.js in jest-inspect repo above) will be ignored, but breakpoints placed in any other files (Jest or other node_modules code) will work correctly when the suite is rerun.

node --inspect is only available in node v6.3.0+ and I'm running on OSX using node v6.4.0 and npm v3.10.3

/cc @kentcdodds

Bug Help Wanted

Most helpful comment

node --inspect --inspect-brk node_modules/bin/jest should work with node 8.4.0 out of the box. I'm so happy this finally works, it was one major issue that was making it hard to debug JavaScript tests.

All 77 comments

run into the same problem today

Also in your example if I run npm run debug

  6
  7     // break won't be triggered
> 8     debugger;
  9
 10     expect(test).toBe(true);
test
ReferenceError: test is not defined

Am I doing something wrong or it doesn't have access to context?

@maximderbin not sure why you're getting that ReferenceError, test should be defined just a few lines above there: https://github.com/snapwich/jest-inspect/blob/master/__tests__/jest.js#L5

edit - just tested, you need to type repl before typing test so the code runs in the proper context.

This is interesting. Is it possible that node's --debug flag doesn't work when using the vm module to create a context?

Any news on this?

Was this ever working before?

I don't think vm.runInContext supports the debugger protocol.

This article mentions port forwarding to support debugging VM code. Not sure if that's relevant.

Beyond that, maybe it's possible to use websockets within the VM (to support the debugger protocol)?

What do you think, @cpojer?

maybe it is possible to run tests without vm context in debug mode?

This issue is the biggest reason why I can't switch to Jest. Any updates or ideas on how to make progress?

I think we need to create a repro without Jest and submit an issue to the node.js bugtracker.

This NodeJS issue looks related: https://github.com/nodejs/node/issues/7593.

Repro case is minimal:

var vm = require('vm');
new vm.Script('debugger;').runInContext(vm.createContext());
debugger;

Will break three times with node debug index.js but only twice with node --inspect --debug-brk index.js

@cpojer do you think it's a good idea to change the content of http://facebook.github.io/jest/docs/troubleshooting.html#tests-are-failing-and-you-don-t-know-why to reflect that this doesn't work yet? I'm happy to submit a PR for this if that would be helpful -- what should the section say? Delete it? Say "coming soon"?

(I love Jest by the way! It makes React testing even more awesome)

I've created a PR for an update to the docs on this: https://github.com/facebook/jest/pull/1998

It seems that node-inspector is not maintained anymore and does not support node 7.*. When I use
node --debug-brk --inspect ./node_modules/react-scripts/node_modules/.bin/jest -i
With CRA and node 7.1 it seems to load correctly in the dev tools and than hang with "waiting for debugger to disconnect" (even though execution is free)

Hi guys, any update on this issue?

IntelliJ Platform (IntelliJ IDEA, WebStorm) will support Jest in the next 2017.1 release (https://youtrack.jetbrains.com/issue/WEB-14979). And v8 inspector is used by default. Will be strange if you can run, but cannot debug.

But it is not Jest issue — it is NodeJS issue. And there is a simple workaround — if you want to debug the only test, you don't need to bother about global state. So, I implemented special test environment for this purpose:

  1. Install module jest-environment-node-debug

    yarn add jest-environment-node-debug --dev
    

    or using npm: npm install jest-environment-node-debug --save-dev

  2. Run using flag --env jest-environment-node-debug

Debug works :)

(Line position is not correct sometimes in the IntelliJ Platform NodeJS Debugger if you use TypeScript and Babel preprocessor together — it is unrelated issue and will be fixed in the 2017.1).

@orta and I were literally talking about this. It works for him in vscode, so we may not need the node-debug environment. I think --debug-brk and starting Jest with -i will work.

I appreciate you building the debug environment, this is exactly how I'd have done it too.

@cpojer V8 Inspector is much better than old v8 debugger protocol — because of that IntelliJ Platform will use V8 inspector by default for NodeJS 7+. So, for me, ability to debug jest using v8 inspector is a vital.

I guess it makes sense to limit this to:

  • Jest runs a single test file
  • It's not in watch mode

One of the problems with this is that you can get the global variable other than global that we pass to a file run in a Jest context. I'd really like to figure out how the node team could fix v8, that seems like the long term fix :(

( For people that are interested, I use VS Code with this launch JSON)

 {
      "name": "Run Tests With Debugger (slower, use npm run watch for normal work)",
      "type": "node",
      "request": "launch",
      "port": 5858,
      "address": "localhost",
      "stopOnEntry": false,
      "runtimeExecutable": null,
      "runtimeArgs": [
        "--debug-brk",
        "./node_modules/.bin/jest",
        "-i"
      ],
      "cwd": "${workspaceRoot}"
    }

screen shot 2016-12-07 at 13 16 12

@orta, can you share your config, too? my source shows up all babel mangled

It's all OSS - https://github.com/artsy/emission 🎉

My solution for runing and debugging single Jest test in IntelliJ Idea.

Node version: v6.9.4

single jest runner

Then just like run any unit test. crtl/command + shift + F10/F9

debugger

For anyone looking for clarification, I was able to hit debugger statements in my code and test files in Node 7.4.0, Jest 18.x, and using @develar's jest-environment-node-debug package (from this comment) with this command:

node --debug-brk --inspect ./node_modules/.bin/jest -i --env jest-environment-node-debug

@trxcllnt tried that, unfortunately doesn't work for me :(

I was also gonna mention https://github.com/nodejs/node/issues/6283 but I see @cpojer is already involved there :)

Node.js 7.5.0 just came out which fixes already some related issues (fixed this one for me)

Thanks for the work around @trxcllnt, without source maps inspector debugging is surprisingly painful with node.

@iammerrick @trodrigues @trxcllnt @snapwich Please try this npm module jest-environment-node-debug

I've made some changes which has fixed node debugging for me using Node v7 and Jest 18.

Also the way I use it by adding "testEnvironment": "jest-environment-node-debug" in my Jest config.

Just FYI I used devtool for debugging

EDIT: Sorry I was too early, I still see some issues (trying to fix them)
EDIT2: Never mind I was trying to use the same environment to run my tests locally which failed because it needs the node debug environment
EDIT3: Thanks @develar for the permission to publish as the original module

When I use jest-environment-node-debug, the jsdom document emulation doesn't seem to be in place. Is there any way to change that?

Between this issue and https://github.com/facebook/jest/issues/2801 causing even usually fail-proof printf-style-debugging to come out incomprehensibly in some cases, I'm finding debugging to be extremely difficult.

@AgentME What do you mean by doesn't seem to be in place? Can you give me an example.

@NikhilVerma The global variables document, window, and the other browser globals aren't present when jest-environment-node-debug is used.

test('foo', () => {
  document.body.textContent = '123';
});

@AgentME I think that's an expected consequence since jest-environment-node-debug is based on jest-environment-node rather than jest-environment-jsdom, the default environment that provides document and other globals to emulate a browser environment.

Wander about the same thing as @AgentME.

FYI

hi. just saw the new node release https://nodejs.org/en/blog/release/v7.6.0/
Not sure this release improve anything as it mention few changes

lib: build node inspect into node (Anna Henningsen) #10187
inspector: add --inspect-brk (Josh Gavant) #11149

@bsr203 I just tested on node v7.6.0 and breakpoints and debugger;statements on tests still do not work

@DanielHoffmann @bsr203 @AgentME Can you please clone https://github.com/NikhilVerma/jest-environment-node-debug-fixed and run npm run devtool and let me know if your breakpoint triggers and you can see document.body.textContent (because I can).

You need NodeJS 7.5.0 or greater

@NikhilVerma it didn't, but document.body.textContent has one line break in it only
I don't know if I am using it correctly though, I installed devtool globally then installed jest-environment-node-debug-fixed from npm registry as a dev dependency in my project then I ran:

devtool ./node_modules/.bin/jest --colors --config=myConfig

The tests run, but the breakpoints do not work. Unlike node --inspect I can not even open the test files in the debugger

@DanielHoffmann You did it wrong :)

git clone [email protected]:NikhilVerma/jest-environment-node-debug-fixed.git
cd jest-environment-node-debug-fixed
npm install
npm run devtool

Basically the requisites are

  • Node v7.5.0 at least
  • Jest 17+
  • Devtool installed
  • Jest CLI ran with "-i" option
  • jest-environment-node-debug package (1.0 if you have jest17 and 2.0 if you have jest18)
  • Make a clone of your jest config and add "testEnvironment": "jest-environment-node-debug" and use that config to run jest (So that your normal tests aren't broken)

Thanks for the steps @NikhilVerma. I have yet to try it out myself, but I thought I'd mention that I hope this is high on the list of things for the Jest team to work on. I imagine that users of Jest (including those at Facebook) would very much like a better debugging experience :) With how easy everything else is with Jest, this is uncharacteristically hard (and should I say... painful 🙀 😉).

I got @develar's tool working with node --inspect-brk ./node_modules/.bin/jest --runInBand --env jest-environment-node-debug.

I still get ReferenceError: window is not defined even after using jest-environment-node-debug-fixed. 😢

Edit: However, I got it to work using bugger https://github.com/buggerjs/bugger

@sugatmahanti Did you get a chance to try the steps I mentioned here? https://github.com/facebook/jest/issues/1652#issuecomment-281985580

@NikhilVerma Thanks I did but once I ran the command, it didn't do anything. It opens the debugger and it immediately closes it with no message whatsoever.

Using the following command:
$ node --inspect --debug-brk ./node_modules/.bin/jest --runInBand -i --env jest-environment-node-debug

I get the following errors:
ReferenceError: window is not defined
only one instance of babel-polyfill is allowed

also debugger seems to be outright ignored just running $ node --inspect --debug-brk ./node_modules/.bin/jest --runInBand

node 7.6.0
Jest 19.0.2
babel-jest 19.0.0

Is this issue still being worked on?

Seems like jest should support the node v6+ --inspect and --inspect-brk commands. Hopefully this will come soon to jest as it appears many people are struggling to debug their unit tests (me included).

This is not a Jest issue. This is a bug in v8/node, see https://github.com/nodejs/node/issues/7593 – please express your concerns there and ask the node or v8 teams to fix this within vm/contextify.

I'm going to close this issue because it isn't actionable from our side. Some workarounds were documented above, that may or not work for you. Once this is fixed in node/v8, it will automatically start working eventually.

Having installed jest-environment-node-debug, I was able to produce a working launch.json config for vscode, using inspector protocol with node 8.

If anyone is interested, this is the minimal configuration needed (assuming port and address are standard):

{
  "name": "Debug Jest",
  "type": "node",
  "request": "launch",
  "runtimeArgs": [
    "--inspect-brk",
    "./node_modules/.bin/jest",
    "-i",
    "--env",
    "jest-environment-node-debug"
  ],
  "cwd": "${workspaceRoot}",
  "protocol": "inspector",
  "console": "integratedTerminal"
}

on windows

        {
            "name": "Debug Jest",
            "type": "node",
            "request": "launch",
            "runtimeArgs": [
                "--inspect-brk",
                "./node_modules/jest/bin/jest.js",
                "-i",
                "--env",
                "jest-environment-node-debug"
            ],
            "cwd": "${workspaceRoot}",
            "protocol": "inspector",
            "console": "integratedTerminal",
            "sourceMaps": true
        }

FYI, this issue should be resolved as of Node 8.4.0 (https://github.com/nodejs/node/pull/14465).

That is awesome. Finally! :)

Thanks to all who got this to work 👏

So is there anything in particular that needs to be done beyond installing latest node v8.4.0? Could someone post their vscode launch.json for this?

This vscode launch config works for me :)

    {
      "name": "Debug Jest tests",
      "type": "node",
      "request": "launch",
      "runtimeArgs": [
        "--inspect",
        "./node_modules/.bin/jest",
        "-i"
      ],
      "cwd": "${workspaceRoot}",
      "protocol": "inspector",
      "console": "integratedTerminal"
    }

You just need to run it in "the new way". That is, with inspect, --inspect or --inspect-brk. See https://nodejs.org/en/docs/inspector/ for more info on the various ways of running it and things that can connect to it.

The aforementioned jest-environment-node-debug is not necessary.

node --inspect --inspect-brk node_modules/bin/jest should work with node 8.4.0 out of the box. I'm so happy this finally works, it was one major issue that was making it hard to debug JavaScript tests.

For those using create-react-app / react-scripts:

./node_modules/.bin/react-scripts --inspect-brk test --env=jsdom --runInBand

Make sure you're on react-scripts@^1.011!

Breakpoints don't hit for me.

  • Windows 10
  • Node 8.4
  • VSCode 1.15.1
  • Jest 20

See the example project here:
https://github.com/sparebytes/jest-debug-example

This is the launch config:

{
    "name": "Debug Jest tests",
    "type": "node",
    "request": "launch",
    "sourceMaps": true,
    "runtimeArgs": [
        "--inspect-brk",
        "--nolazy",
        "./node_modules/jest/bin/jest.js",
        "-i"
    ],
    "cwd": "${workspaceRoot}",
    "protocol": "inspector",
    "console": "integratedTerminal"
}

@sparebytes in your console, check your node --version, make sure it's 8.4. The following launch config worked for me with your same specs:

  {
    "name": "Debug Jest tests",
    "type": "node",
    "request": "launch",
    "program": "${workspaceRoot}\\node_modules\\jest\\bin\\jest.js",
    "args": [
      "--runInBand",
      "--no-cache"
    ],
    "runtimeArgs": [
      "--inspect-brk"
    ],
    "cwd": "${workspaceRoot}",
    "protocol": "inspector",
    "console": "integratedTerminal"
  }

Still doesn't work for me on 8.4.0 and I've tried everything.

It looks like the break points become red (get activated) after the tests have finished.. Any ideas?

+1
It does not work for me too

@yevhenchmykhunep did you give this a shot?

./node_modules/.bin/react-scripts --inspect-brk test --env=jsdom --runInBand

By @Timer

I'm having the issue on node v10.5.0 and [email protected] node --inspect --inspect-brk ./node_modules/jest/bin/jest.js

The break on first line works, but the debugger calls don't stop :(

Looks like it not the jest problem, but nodejs problem. I Having the same issue with debugging my application as well. I'm using node v8.11.3

I can get the debugger to spawn and hit debugger lines in node 8.

"test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand -t",

and

nvm exec 8 yarn test:debug

However, this debugger line will not cause a stop:

describe.skip('With Enzyme', () => {
  it('ArticleSidebar component displays', () => {
    debugger;

This line will:

// this code is in not in tests
import { config } from './nextConfig';
let log, logError;
debugger; 

So the moral of the story for me appears to be: don't expect debugger breaks to be hit if they are in Jest test code. Why? Maybe someone smarter than me wants to figure that out 😸

For those still stuck with this problem, debugging in Chrome DevTools works with the debugger statement. Not an ideal solution, but a decent workaround:

To debug in Google Chrome (or any Chromium-based browser), simply open your browser and go to chrome://inspect and click on "Open Dedicated DevTools for Node", which will give you a list of available node instances you can connect to. Simply click on the address displayed in the terminal (usually something like localhost:9229) after running the above command, and you will be able to debug Jest using Chrome's DevTools.

The Chrome Developer Tools will be displayed, and a breakpoint will be set at the first line of the Jest CLI script (this is done simply to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a "play" button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the debugger statement, execution will pause and you can examine the current scope and call stack.

Source: https://jestjs.io/docs/en/troubleshooting#tests-are-failing-and-you-don-t-know-why

@jchani even with this method, debug statements inside tests will still not break. As @jcollum pointed out. Even with break on first line enabled. Break points inside tests is the type we all want more than any other. Debugging why a test stopped working is a pita without this ability.

https://github.com/vuematerial/vue-material/pull/1840 @Samuell1 why do you want to stick with jest 22 when we have 4 tests failing on dev... imo no commit should ever be allowed with failing tests.

For Vue users: if your debugger statements aren't working... try moving them to your component instead of the jest code, do as little as possible in jest and just check the state of your fixtures... at least until the nodejs team fixes this issue.

My debugger calls are ininput-speed.vue. I realise this is not ideal, but it beats not having debugging or forgoing tests because they are too hard to build.

import Vue from 'vue'
import { mount } from 'avoriaz'
import f1 from '../fixtures/input-speed.vue'

test('should work with phones autocorrect', async () => {
  const wrapper = await mount(f1, {})
  const vm = wrapper.vm

  await wrapper.vm.$nextTick()

  // should work with android autocorrect without waiting
  expect(vm.form.server).toBe('autocorrect')
  expect(vm.noBind).toBe('Not data binded')  // Should work without data binding
})

Adding this for anyone having this issue while using the --watch option - debugger statements are ignored with --watch, however adding --no-cache fixes the issue. I can confirm that the following works consistently on node 10.8.0:

node --inspect-brk node_modules/.bin/jest --runInBand --no-cache --watch

for node 6.x, instead of node --inspect-brk, try node inspect (note, the lack of hyphens)

nvm

This extension has helped me: https://chrome.google.com/webstore/detail/nodejs-v8-inspector-manag/gnhhdgbaldcilmgcpfddgdbkhjohddkj/related?hl=en

It detects node --inspect and opens devTools in Chrome for that websocket. debugger statements and breakpoints set manually on devtools has worked!

It's funny, it seems like i have better luck here if I turn OFF Node Inspector Manager and use chrome://inspect instead.

@jcollum As the developer of NiM... anything, in particular, I should be aware of?

Sorry, I don't have anything specific here. Sometimes hitting a breakpoint in a file that's behind a sourcemap is just flaky. Next time I need to debug a jest test I'll give NIM another shot.

I wanted to report back that we encountered the same problem as mentioned by @brien-givens

As he said adding --no-cache solves the problem for us (details see here: https://github.com/facebook/jest/issues/1652#issuecomment-412692363)

@brien-givens thanks for sharing your solution :-)

For me the issue was with two *.test.js files with the same name (located in different folders). When I removed one of them, debugger was hit in the other without problems.
Configuration:
"name": "Debug Jest Test", "type": "node", "request": "launch", "program": "${workspaceRoot}/node_modules/jest/bin/jest", "args": [ "${fileBasenameNoExtension}", ], "console": "integratedTerminal"

Was this page helpful?
0 / 5 - 0 ratings