Magnifier, pencile and notebook

Debugging React Unit Tests in a Monorepo with NX

After using NX for over a year, it’s frustrating that there is very sparse documentation on debugging with VSCode or using it with React.

I finally decided to dig into setting up my debugging profile for our unit tests (because I was fed up with console.log – ing them).

I found this YouTube video by Juri, which is 4 years old and does not work with the latest NX version, but it gave me a hint on how the config should be structured.

To enable debugging of your jest unit tests you need to:

  • Set the Debug: Auto-attach option to “Smart” or “Always”. (Smart is more performant, preventing it from attaching to every script you run).
  • Create a launch.json file in the .vscode folder in the root of your monorepo, and add the following configuration to it:
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug Tests",
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceFolder}/node_modules/nx/bin/nx.js",
      "cwd": "${workspaceFolder}",
      "args": ["run-many", "-t", "test", "--skipNxCache"]
    }
  ]
}

Explanation: In the launch.json you run the nx.js binary and execute all the test commands in your monorepo. It’s important to skip the cache, else your breakpoints will be hit only when you change something related to the test you want to debug.

Now you can add a breakpoint and hit F5 to debug your unit tests! 🎉 🎉 🎉


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.