Search code examples
node.jsreactjstypescriptjestjsts-jest

Running Jest from node in a CRA application with expose-gc


I'm having issues with memory leaks coming from running my test suites with Jest where memory usage keeps growing with each suite.

After searching through the net, I've found that this could be related to a garbage-collector behaviour, and multiple Github threads suggest running this command:

node --expose-gc ./node_modules/jest/bin/jest.js --coverage --runInBand --logHeapUsage

The issue is that my project uses React (with CRA not ejected) and Typescript, so whenever I run this script it throws a Syntax error because of Typescript.

I've tried installing ts-jest library but it does not work. It may be related, but running the ts-jest setup init complains about already having a configuration due to CRA.

I've been searching and I have not found anything, since all related threads are about the known memory leaks Jest has, but none explain how to execute the node command with the expose-gc in a project with React and Typescript.

  • Is there any way I can expose the GC to the Jest script used by CRA so I can keep using the same configuration as until now?
  • Otherwise, how can I execute the node --expose-gc jest parsing my files so that it does not throw an error?
  • I'd also need to use the --inspect-brk to see where the leak comes from, so even if the --detect-leaks works, I still need to find a way to execute my Jest config from node command.

Thank you!


Solution

  • After reviewing the documentation from Jest, I've seen this section which suggests to run the debug configuration in VS Code calling react-scripts. After playing a little bit with it, this is the command that got it working:

    node --inspect-brk node_modules/react-scripts/scripts/test.js --no-cache --env=jsdom --runInBand

    As you can see, you have to call the test.js file inside react-scripts directly, and then you can send all the arguments you want to Jest, as you'd normally do when running tests directly from the terminal of your project.

    If you execute this script:

    node --inspect-brk node_modules/react-scripts/bin/react-scripts.js test --no-cache --env=jsdom --runInBand

    You will be able to attach to the node debugger, but you won't be able to set debugger stops in your test files, as it will attach to the main process, which is react-scripts (and not the test script itself).

    Hope this might help someone in a future!