Search code examples
debuggingjestjscreate-react-app

how to debug jest unit tests on create-react-app?


I use create-react-app and I would like to debug my unit tests

as Jest documentation says, debugging is possible using this command:

node --debug-brk --inspect ./node_modules/.bin/jest -i [any other arguments here]

unfortunately, it's not working with create-react-app. I got this error instead:

node --debug-brk --inspect ./node_modules/.bin/jest -i
Debugger listening on port 9229.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
    chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=localhost:9229/node
Debugger attached.
module.js:457
    throw err;
    ^

Error: Cannot find module '/Users/asafkatz/dev/newmaps/node_modules/.bin/jest'
    at Function.Module._resolveFilename (module.js:455:15)
    at Function.Module._load (module.js:403:25)
    at Timeout.Module.runMain [as _onTimeout] (module.js:590:10)
    at tryOnTimeout (timers.js:232:11)
    at Timer.listOnTimeout (timers.js:202:5)
Waiting for the debugger to disconnect...

what is the proper way to debug jest unit test on create-react-app?


Solution

  • Running jest along with Chrome DevTools appears to be problematic (see this issue).

    The problem:

    You can start the node debugger using the new V8 Inspector protocol using the aforementioned command lines (adjust the jest path):

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

    Meaning:

    # node params
    --debug-brk: start debugger, expose external interface, and break at the first line
    --inspect: use the new V8 Inspector protocol in the debugger
    
    # jest params
    --runInBand: do not fork (make it debuggable)
    

    Then you can use Google Chrome and connect to the given URL or use this useful extension to do it automatically for you.

    Unfortunately as of now the debugger; calls in test code will not be taken into consideration.

    The workaround

    To work around the problem, for now, you can download a GUI debugger compatible with the plain V8protocol such as Visual Studio Code. In order to use it, you have to start the node debugger without the --inspect flag:

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

    Then from VCS you can navigate to the project folder, enter the Debugging section, create the standard debugging configurations, and run the Attach to Process config.