Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

node --inspect-brk jest --runInBand --watch doesn't stop on breakpoint or debugger statement. #6683

Closed
nolazybits opened this issue Jul 12, 2018 · 38 comments

Comments

@nolazybits
Copy link

🐛 Bug Report

node --inspect-brk jest --runInBand --watch
doesn't stop on breakpoints or debugger statement whereas
node --inspect-brk jest --runInBand
will (no --watch flag)

Noe: It is using ts-jest 23.0.0

jest.config.js

module.exports = {
    globals: {
        "ts-jest": {
            skipBabel: true,
            enableTsDiagnostics: true,
            disableSourceMapSupport: true
        }
    },
    roots: [
        "<rootDir>/src",
        "<rootDir>/tests"
    ],
    transform: {
        "^.+\\.tsx?$": "ts-jest"
    },
    testRegex: "(/tests/.*.(test|spec)).ts$",
    moduleFileExtensions: [
        "js",
        "ts",
        "json",
        "node"
    ],
    setupTestFrameworkScriptFile: "jest-extended",
    verbose: true
};

Expected behavior

I would expect debugging to work with --watch

Run npx envinfo --preset jest

it errors with

(node:2536) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '1' of null
node --version
v10.0.0

jest version
23.4.0

Thanks

@phnah
Copy link

phnah commented Jul 13, 2018

I'm having a similar problem.

Node: v8.9.0
jest: v23.4.0

@jamietre
Copy link
Contributor

jamietre commented Jul 17, 2018

I'm having this problem also. At first I thought it was Visual Studio Code issue; there seems to be a problem with debugging in the latest release as well which confuses things further.

But the workarounds and downgrading vscode didn't work for me. I had to downgrade Jest to 22.4.4 to get debugging to work correctly again. This could also be a ts-jest issue, since I've been unable to run ts-jest@23 for different reasons.

node: v8.9.3
jest: 23.4.1
ts-jest: 22.4.6

@mgibson91
Copy link

@jamietre Thanks! The latest packages weren't working for me but that combination does! For the sake of any others, here is my config:

Packages

  • jest: 22.4.4
  • ts-jest: 22.4.6
  • node: 9.2.0

Webstorm steps

  • Add new Jest config
  • Add Compile Typescript step (not sure if this is neccessary as when I removed it, still worked but could be cache related)

jest.config.js

module.exports = {
  transform: {
    "\^.*ts$": "ts-jest",
  },
  testMatch: [
    '<rootDir>/test/*.spec.ts',
    '<rootDir>/test/**/*.spec.ts',
  ],
  moduleFileExtensions: [
    "ts",
    "js",
    "json",
  ],
  moduleNameMapper: {
    "@/(.*)$": "<rootDir>/$1",
    "^src/(.*)$": "<rootDir>/src/$1",
    "^core/(.*)$": "<rootDir>/src/core/src/$1",
  },
  testEnvironment: 'node',
};

@jamietre
Copy link
Contributor

jamietre commented Jul 18, 2018

@mgibson91 I ended up at Jest 23.1.0. There are some behavior changes between 22.4.4 and 23.1.0 (bug fixes perhaps?) related to mock resolution when writing typescript mocks for javascript files, which we had explicit tests for because it was confusing.

So that may not matter to you but just wanted to let you know everything works at least up to 23.1.0 (with ts-jest 22.4.6) for us.

@mgibson91
Copy link

@jamietre Good to know, thanks!

@jamietre
Copy link
Contributor

jamietre commented Jul 19, 2018

I started having trouble again after downgrading to 23.1.0, and after pulling some hair out I got things to work reliably by using --no-cache when invoking Jest. This also seems to solve the problem with the latest Jest release too. It's not clear to me why just downgrading Jest to the version that had been working reliably before didn't work, but there are so many moving parts that have changed in last few weeks (VS Code version, typescript, jest, ts-jest) I assume there are other things involved.

I tried the following:

jest --inspect --watch

Breakpoints are unverified. Debugging doesn't work at all

jest --clearCache
jest --inspect --watch

Breakpoints are verified. Stops on breakpoints the first run only. After changing something resulting in tests restarting, vscode still shows verified breakpoints, but the debugger doesn't work any more.

jest --no-cache --inspect --watch

Seems to work reliably.

So there's something wrong with the way sourcemaps are cached, apparently, and it isn't just old/invalid cached information lying around from an older version of something, since clearing the cache only results in it working once.

@larrybotha
Copy link

larrybotha commented Jul 25, 2018

thanks @mgibson91, the versions you provided work for me:

"jest": "22.4.4",
"ts-jest": "22.4.6"
node: v9.5.0

running the following command:

$ node --inspect $(npm bin)/jest --watch

Breakpoints were not being hit when using [email protected]

@sokra
Copy link
Contributor

sokra commented Jul 27, 2018

I assume #6647 causes this issue.

Blacklisting "in band" mode when using the watch mode fixes the issue, since tests are executed in workers, freeing the main process.

runInBand is backlisted when watching. This also breaks debugging in watch mode for me. Removing --watch and only using --runInBand works, but slows me down, because jest startup has to paid every time, while restarting tests in watch mode is faster.

I would say always use workers in watch mode expect when passing --runInBand.

cc @mjesun

@ranyitz
Copy link
Contributor

ranyitz commented Jul 30, 2018

https://github.com/facebook/jest/blob/fb2a6ac4d3f4e9530941e24030b52f3d506aa2de/packages/jest-cli/src/TestScheduler.js#L88-L94

What do you say about checking process.execArgv, look for --inspect/--inspect-brk and runInBand as a result?

Do we have a reason not to runInBand while debugging?

@geekox86
Copy link

Hi awesome Jest team,

Thank you for your wonderful efforts to make our coding workflows better.

I unfortunately suffer from the same issue with the following versions:

jest 23.5.0
ts-jest 23.1.3
typescript 3.0.1
node 10.7.0

Here is my jest.config.json:

{
  "collectCoverage": true,
  "coverageReporters": ["text"],
  "moduleFileExtensions": ["js", "jsx", "ts", "tsx"],
  "testEnvironment": "node",
  "testMatch": ["**/?(*.)test.ts?(x)"],
  "transform": { "\\.tsx?$": "ts-jest" }
}

And this is my script to run tests:

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

Breakpoints only hit and stop if I have a single test file. However, with multiple test files, no breakpoint is respected, including using debugger keyword.

Any clue is appreciated.

Thank you!

@thymikee
Copy link
Collaborator

If you're in --watch mode and having more than 1 test, Jest will spawn a worker, which supposedly doesn't work with debugger currently. Removing --watch flag will let you debug tests normally.

@jamietre
Copy link
Contributor

jamietre commented Aug 24, 2018

@sokra

runInBand is backlisted when watching. This also breaks debugging in watch mode for me. Removing --watch and only using --runInBand works, but slows me down, because jest startup has to paid every time, while restarting tests in watch mode is faster.

@thymikee

If you're in --watch mode and having more than 1 test, Jest will spawn a worker, which supposedly doesn't work with debugger currently. Removing --watch flag will let you debug tests normally.

Jest definitely doesn't disable runInBand always in watch mode, per @sokra comment, since this is pretty much the only way I've ever used debugging with Jest (in watch mode). Maybe it disables it with more than 1 test, but I've probably never tried to do this intentionally. Usually when debugging, it's dealing with a specific test.

My problem was always when running just one test, and I was able to fix it only by disabling the cache. I am guessing there are more things at play here then just runInBand + watch.

In any event, this certainly seems to be involved somehow. EIther way I think Jest should fail if someone tries to use incompatible options instead of just "blacklisting" it, resulting in very confusing outcomes.

@geekox86
Copy link

geekox86 commented Aug 24, 2018

Thank you guys for your prompt answers.

Just being digressive here, how does your debugging workflow with Jest look like then? Do you switch back and forth between Jest output and manual CLI to debug failed ones one by one? How can this be more effective?

Thank you again for your help!

@jamietre
Copy link
Contributor

jamietre commented Aug 24, 2018

Do you switch back and forth between Jest output and manual CLI to debug failed ones one by one? How can this be more effective?

It's not typical for me to have more than a single test that needs debugging at one time; having Jest debugging only work for one test doesn't seem like that big a deal to me (if indeed that's the only problem here). That is - I wouldn't usually start work on a new test while an existing one was broken. If I happened to have some regression that broke lots of things, I'd just pick one to deal with, and fixing the underlying issue would likely fix them all.

The bigger issue (for me anyway) is that it's been very confusing to understand why it wasn't working and get it to work reliably.

@geekox86
Copy link

Cheers man

@ravihugo
Copy link

Ran into this, took about 5 hours thinking my VSCode was malfunctioning. If anyone else has a workflow of running jest in watch mode, then using VSCode to "Attach by Process ID", I recommend modifying your command line to:

jest --watch --no-cache --runInBand

@ravihugo
Copy link

No idea why, but this stopped working for me now. I think it's something to do with the workers being created when in watch mode. I don't think there is a way to prevent it now. Maybe I'm missing something.

@DanielHoffmann
Copy link

@ravihugo I can confirm that jest --watch --no-cache --runInBand used to work a couple of months ago, but apparently no longer does. I think I am picking up a newer version of some dependency that broke this little trick.
node v8.12.0
jest v23.6.0

I guess for now we need to pick if we want watch mode or breakpoints

@aleclarson
Copy link
Contributor

aleclarson commented Nov 24, 2018

This seems like a very important issue. Could we please get a Jest core contributor to look into this deeper?

Removing --watch and only using --runInBand works, but slows me down, because jest startup has to paid every time, while restarting tests in watch mode is faster.

Should we consider bundling Jest using Rollup for faster startup performance? Or maybe Yarn PNP can be utilized here?

@aleclarson
Copy link
Contributor

aleclarson commented Nov 24, 2018

Note: Use VS Code if you can! (see here) It's way faster and less finnicky than ndb.

The ndb solution

Using ndb, we can debug child processes (so --runInBand should not be used). Breakpoints and debugger statements are respected. :)

note: You may need to set a breakpoint before your debugger statements are respected. :(

Directions

  1. Run npm install -g ndb
  2. Add "debug": "jest --watch" to your NPM scripts
  3. Run ndb (no args) from your package's root directory
  4. Run the NPM script from within ndb (see here)

@benterprise
Copy link

benterprise commented Dec 10, 2018

I also can't get debuggers to catch using chrome node devtools, the solutions above don't seem to work. The initial breakpoint is caught but none of the debuggers I'm putting into the actual file are catching.

@jamietre
Copy link
Contributor

jamietre commented Dec 10, 2018

I also can't get debuggers to catch using chrome node devtools, the solutions above don't seem to work. The initial breakpoint is caught but none of the debuggers I'm putting into the actual file are catching.

You're absolutely sure you're only running Jest against one file at a time?

jest --watch --no-cache --runInBand

.. with only one test continues to work fine for me, on latest release of Jest 23.6.0.

Running only one test is very important. --runInBand is ignored with more than one test.

@benterprise
Copy link

benterprise commented Dec 10, 2018

@jamietre

I've scaled my test back to this:

test.only("it does some shit", () => { debugger })

I'm running yarn test:debug aTest.test.js
from this package.json

{
  "scripts": {
    "test": "jest --colors",
    "test:debug": "node --inspect-brk node_modules/.bin/jest --watch --no-cache --runInBand"
  },
  "jest": {
    "verbose": true,
    "collectCoverage": false,
    "collectCoverageFrom": [
      "src/**/*.{js,jsx}"
    ],
  },
  "devDependencies": {
    "@babel/cli": "^7.0.0",
    "@babel/core": "^7.2.0",
    "@babel/plugin-transform-object-assign": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "babel-core": "^7.0.0-bridge",
    "babel-jest": "^23.6.0",
    "babel-loader": "^8.0.0",
    "jest": "^23.6.0",
    "regenerator-runtime": "^0.12.1",
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0"
  }
}

Chrome will pause here:

(function (exports, require, module, __filename, __dirname) { 
/**
 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

const importLocal = require('import-local');

if (!importLocal(__filename)) {
  require('jest-cli/bin/jest');
}

});

And in my terminal stops here:

 PASS  test/request/aTest.test.js
  ✓ it does some shit (4ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.309s
Ran all test suites matching /aTest.test.js/i.

Active Filters: filename /aTest.test.js/
 › Press c to clear filters.

Watch Usage
 › Press a to run all tests.
 › Press f to run only failed tests.
 › Press o to only run tests related to changed files.
 › Press p to filter by a filename regex pattern.
 › Press t to filter by a test name regex pattern.
 › Press q to quit watch mode.
 › Press Enter to trigger a test run.

@hulkish
Copy link
Contributor

hulkish commented Dec 25, 2018

how about just NODE_OPTIONS="--inspect-brk"?

@jamietre
Copy link
Contributor

@benterprise if I am not mistaken that does not satisfy the criteria of "running only one test". Jest is still going to disable runInBand because there are multiple tests matched by the runner. It still has to load all the files and parse them to determine that there's a ".only" somewhere.

Try again using a pattern as the final command line argument that will result in only a single test file being matched.

@jonsmithers
Copy link

I was encountering a similar issue running just via create-react-app's react-scripts. I got it to work by appending --no-watch to our debug run script like so:

    "test:debug": "react-scripts --inspect-brk test --env=jsdom --runInBand --no-watch",

react-scripts 2.1.4 appears to enable watch mode by default.

@brianyang
Copy link

debugger wasn't stopping for me. I read through most of this thread and needed to watch for changes.

I'm using react-scripts 2.1.5

just running one spec and passing the no-cache flag worked for me

npx react-scripts --inspect test singleSpec --no-cache

@federicobarera
Copy link

Same, the trigger is the '--watch' flag. Running without it makes breakpoints and debugger hit

@wasker
Copy link

wasker commented Mar 22, 2019

After much experimentation, I was able to get TypeScript spec debugging working with VSCode and Jest v24.x.

My setup:

  • NodeJS v10.15.3 (latest LTS)
  • Jest v24.x
  • TS-Jest v23, v24
  • Latest VSCode

Launch.json:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Debug unit tests",
            "runtimeArgs": [
                "--inspect-brk",
                "--nolazy",
                "node_modules/jest/bin/jest",
                "--runInBand",
                "--watch",
                "--config=path/to/jest.config.json",
            ],
            "sourceMaps": true,
            "disableOptimisticBPs": true,
            "cwd": "${workspaceFolder}",
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen",
            "port": 9229,
            "env": {
                "NODE_ENV": "test"
            }
        }
    ]
}

Jest is configured with preset ts-jest/presets/js-with-ts.

TypeScript is configured with "sourceMap": true.

Note that even watch is working!

@molszanski
Copy link

This worked for me.
Breakpoints work and watch mode works.
"${fileBasenameNoExtension}" allows you test currently open file

{
      "type": "node",
      "request": "launch",
      "name": "Watch Jest Current File",
      "runtimeArgs": [
        "--inspect-brk",
        "--nolazy",
        "${workspaceFolder}/node_modules/.bin/jest",
        "${fileBasenameNoExtension}",
        "--colors",
        "--watch",
        "--runInBand",
        "--config",
        "jest.config.js"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "disableOptimisticBPs": true,
      "sourceMaps": true,
      "windows": {
        "program": "${workspaceFolder}/node_modules/jest/bin/jest"
      },
      "port": 9229
    }

@SimenB
Copy link
Member

SimenB commented May 1, 2020

Is this still an issues in Jest 25? We've had a few fixed to source map handling in the last few releases

@secustor
Copy link

This is still an issue for in v27.0.3

@VitorLuizC
Copy link

Seems like node [args] node_modules/.bin/jest doesn't work anymore because it isn't JavaScript.

> const@ test /home/vitorluizc/projects/playground/experiments/const
> node --expose-gc node_modules/.bin/jest

/home/vitorluizc/projects/playground/experiments/const/node_modules/.bin/jest:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^

SyntaxError: missing ) after argument list
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

something similar happens runnig with npx

> const@ test /home/vitorluizc/projects/playground/experiments/const
> npx -n --expose-gc jest

ERROR: --node-arg/-n can only be used on packages with node scripts.

but I found that running jest/bin/jest.js works like a charm!

> const@ test /home/vitorluizc/projects/playground/experiments/const
> node --expose-gc node_modules/jest/bin/jest.js

 PASS  src/main.test.ts
  Const | unit test
    ✓ creates objects with received value as property (2 ms)
    ✓ allows comparison of objects with same value
    ✓ doesn't cause memory leaks (1023 ms)

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        2.12 s, estimated 3 s
Ran all test suites.

@Stamo-Gochev
Copy link

Stamo-Gochev commented Oct 8, 2021

I am getting a similar error:

$ node --inspect-brk node_modules/.bin/jest --runInBand
Debugger listening on ws://127.0.0.1:9229/3424c89c-ecd2-4470-bcfc-c930706eca56

For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
D:\...\node_modules\.bin\jest:2
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
          ^^^^^^^

SyntaxError: missing ) after argument list
    at Module._compile (internal/modules/cjs/loader.js:721:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Waiting for the debugger to disconnect...

Testing with node v10.16.0.

@anthonyvialleton
Copy link

I confirm that node debugger mode does not start Jest. Testing with node v16.13.0:

$ node --inspect-brk ./node_modules/jest/bin/jest.js -i src/tests

Debugger listening on ws://127.0.0.1:9229/5ffa8ac7-5609-4679-af25-ca6f84386fc9
For help, see: https://nodejs.org/en/docs/inspector

I also tried with Jest binary (as document): $ node --inspect-brk ./node_modules/.bin/jest -i src/tests without success.

PS: There is no error output.

@maaaaagda
Copy link

I have same issue as @anthonyvialleton, node v16.13.0, MacOS Monterey
node --inspect ./node_modules/.bin/jest works though but not in debug mode, it starts the tests. I'm also able to debug tests with launch.json config

@SimenB
Copy link
Member

SimenB commented Feb 24, 2022

OP reports (node:2536) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '1' of null error, which no longer happens.

This issue is more than 3.5 years old at this point, and has had lots of examples and workarounds it's hard to say what the current state is.

So I'll close this and ask anyone still having issues to open up a new issue with minimal reproduction steps (i.e. no VS code, no CRA etc.).

I realise this is a sucky message, but the issue in the OP is fixed, so a new issue should be filed with any new issues with debugging.


Anecdotally, debugging works fine for me using chrome with watch mode, so it's not completely broken.

@SimenB SimenB closed this as completed Feb 24, 2022
@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 27, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests