nrwl / nx

Smart Monorepos · Fast CI
https://nx.dev
MIT License
23.2k stars 2.31k forks source link

How To Debug Jest in VSCode #805

Closed sforner405 closed 5 years ago

sforner405 commented 5 years ago

Is there a possibility to debug JEST tests in VSCode? Unfortunately we could not find a setup, where the test stops at a breakpoint. Thanks!

rinckd commented 5 years ago

In your launch .json file you'll want to use something like this:

{
      "type": "node",
      "request": "launch",
      "name": "Jest Test",
      "program": "${workspaceFolder}\\node_modules\\jest\\bin\\jest",
      "args": ["--runInBand", "--config=${workspaceFolder}\\jest.config.js"],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen"
},
skorunka commented 5 years ago

That works. Breakpoint is hit. But I'm getting this error:

 FAIL  apps/el/admin/src/app/app.component.spec.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    <project_path>\apps\el\admin\src\app\app.component.html:2
    <div style="text-align:center">
    ^

    SyntaxError: Unexpected token <

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
      at apps/el/admin/src/app/app.component.ts:26:15
      at Object.<anonymous> (apps/el/admin/src/app/app.component.ts:30:2)

It is a nrwl workspace with one app and one lib, no code changes.

npm run test works - all tests are green

Any idea?

sforner405 commented 5 years ago

Just found a solution. Had to adjust my launch.json and use the jest plugin in vscode.

Here is an example launch.json:

"configurations": [
        {
            "type": "node",
            "name": "vscode-jest-tests",
            "request": "launch",
            "program": "${workspaceFolder}/node_modules/.bin/ng",
            "args": [
                "test",
                "lib-name",
                "--runInBand",
                "true"
            ],
            "cwd": "${workspaceFolder}",
            "console": "integratedTerminal",
            "internalConsoleOptions": "neverOpen"
        },
        {
            "name": "Jest Tests",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/node_modules/.bin/ng",
            "args": ["test","--runInBand","-i"],
            "outFiles": ["${workspaceRoot}/dist/**/*"],
            "cwd": "${workspaceFolder}"
        }
    ]
skorunka commented 5 years ago

@sforner405 Hi, do you really have nrwl workspace? I can see the lib name is hardcoded in the args?

sforner405 commented 5 years ago

@skorunka Yes using nrwl. The lib name has to be hardcoded (and has to be changed) if you only wan't to debug a specific test. Maybe it works with the change detection too, but haven't tried that yet. With this setup you can debug single operations from vs code by using the vs-jest plugin and start debugging directly in the methods. If you don't mind running all the tests you can remove the lib-name

skorunka commented 5 years ago

I see, that makes sense.

mihalcan commented 5 years ago

I use Windows and in my case "program": "${workspaceFolder}/node_modules/.bin/ng", didn't work throwing _Cannot launch program 'your_path\nodemodules.bin\ng' because corresponding JavaScript cannot be found. or _Cannot launch program 'your_path\nodemodules.bin\ng'; setting the 'outFiles' attribute might help when removing outFiles property.

Replacing .bin' folder with the actual/node_modules/@angular/cli/bin/ng`:

{
      "name": "vscode-jest-tests",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/node_modules/@angular/cli/bin/ng",
      "args": ["test", "lib-name", "--runInBand=true"],
      "cwd": "${workspaceFolder}",
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "trace": "all"
}

helped in my case, I can set breakpoints and debugging works as expected. The only downside - you have to provide lib or app name, as when running all tests, breakpoints are not hit.

skorunka commented 5 years ago

For some reason, when I put breakpoint in or enter into the method under the test, it always highlight the last line in the file: image and in the BREAKPOINTS window I can see the BP line number is 3803: image

It looks like the BP is in the bundled file? Any idea why it might happens?

Thanks.

Cammisuli commented 5 years ago

@skorunka try running with the flag --codeCoverage false. By default the codeCoverage flag is set to true. This causes a bunch of instanbul instrumented code that would mess up sourcemaps for files outside of the actual spec file.

For the above launch.json config, it would look like this:

{
      "name": "vscode-jest-tests",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/node_modules/@angular/cli/bin/ng",
      "args": ["test", "lib-name", "--runInBand=true", "--codeCoverage=false"],
      "cwd": "${workspaceFolder}",
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "trace": "all"
}
skorunka commented 5 years ago

@Cammisuli it helped and it works! Thank you.

mathpaquette commented 5 years ago

@all why this issue still opens? One thing it doesn't cover is the fact that weren't able to use the --watch switch while debugging. Anyone has a solution for it?

mathpaquette commented 5 years ago

Just found that Jest support for Angular too much greenfield for those are curious about it. The open source community is very small, there are unsolved issues still going on, since Angular team doesn't support it officially you might lose a lot of time figuring out unsupported use cases or regressions. On the second hand, you might want consider using Jest for testing utility library which not includes DOM manipulations.

What do you guys think?

vsavkin commented 5 years ago

This is a blog post covering debugging Jest: https://blog.nrwl.io/debugging-nx-in-vs-code-cb1dbe9eeeba

Let me know if it answers your questions.

snebjorn commented 4 years ago

this doesn't appear to work anymore I'm trying to debug a typescript lib built using @nrwl/node. Here's the config

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "vscode-jest-tests",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/node_modules/@nrwl/cli/bin/nx", // adjusted it to use the nx cli.
      "args": [
        "test", 
        "akita", 
        "--runInBand=true", 
        "--codeCoverage=false", 
        "--testNamePattern=setEntities", 
        "--testFile=${workspaceFolder}/libs/akita/src/__tests__/setEntities.spec.ts"
      ],
      "cwd": "${workspaceFolder}",
      "console": "internalConsole"
    }
  ]
}

It doesn't hit any breakpoints. Please advice

ghost commented 4 years ago

this doesn't appear to work anymore I'm trying to debug a typescript lib built using @nrwl/node. Here's the config

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "vscode-jest-tests",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/node_modules/@nrwl/cli/bin/nx", // adjusted it to use the nx cli.
      "args": [
        "test", 
        "akita", 
        "--runInBand=true", 
        "--codeCoverage=false", 
        "--testNamePattern=setEntities", 
        "--testFile=${workspaceFolder}/libs/akita/src/__tests__/setEntities.spec.ts"
      ],
      "cwd": "${workspaceFolder}",
      "console": "internalConsole"
    }
  ]
}

It doesn't hit any breakpoints. Please advice

Mine is

  "program": "${workspaceFolder}\\node_modules\\@nrwl\\cli\\bin\\nx.js",

not

 "program": "${workspaceFolder}/node_modules/@nrwl/cli/bin/nx"

Not sure if that is the issue though...

JoepKockelkorn commented 4 years ago

Indeed, can confirm that suddenly it stopped working. Found a workaround for now by using the angular cli.

snebjorn commented 4 years ago

Wonder if this can be setup to work with the new single file debugging in VSCode https://code.visualstudio.com/updates/v1_47#_single-file-debugging

ghost commented 4 years ago

Agree this is no longer working for me, it seems to be (for me) because nx test translates to nx run my-app:test, and therefore the testNamePattern may not be found if the current file is not part of the main app project.

If I add the project name into args in launch.json each time then I can get it to debug. There is probably a better way of fixing this but I haven't had time to investigate.

KerickHowlett commented 3 years ago

Pardon my ignorance, but I'm still fairly unfamiliar with the Jest Launcher: I was just wondering if there's a way to configure the launcher to work with a file/library/app you're actively working on and not hard code it into the config args?

For example, say I'm trying to debug some file in my form library, is there a way to just run the debugger for the file I'm presently looking at without first having to configure the project name into the launcher config file?

ebrehault commented 2 years ago

FYI, this small utility allows to create a launch.json configuration without hard-coding the app or lib name: https://github.com/ebrehault/nx-jest-launcher

fynnlyte commented 2 years ago

Pardon my ignorance, but I'm still fairly unfamiliar with the Jest Launcher: I was just wondering if there's a way to configure the launcher to work with a file/library/app you're actively working on and not hard code it into the config args?

For example, say I'm trying to debug some file in my form library, is there a way to just run the debugger for the file I'm presently looking at without first having to configure the project name into the launcher config file?

What works well for me without creating any config files and not just for jest tests:

  1. Open a VSCode debug terminal: F1 -> "Debug: Javascript Debug Terminal"
  2. Inside the terminal, execute whatever test you want to debug, e.g. nx test my-lib
hanspoo commented 2 years ago

Hi, i have the same problem, very weird, nx test a library doesn’t stop on breakpoints, but in apps it works. I’ve found a workaround:

it works when running from the library folder, ie:

cd libs/app-role-demo/ then:

nx test or nx test app-role-demo

and voila

github-actions[bot] commented 1 year ago

This issue has been closed for more than 30 days. If this issue is still occuring, please open a new issue with more recent context.