How to solve the Memory Leak problem on Node.js while running Jest

A step-by-step guide to solving the JavaScript heap out-of-memory error while running test cases on Node JS

Gonzalo Fernandez Plaza

--

A step-by-step guide to solving the JavaScript heap out-of-memory error while running test cases on Node JS
A step-by-step guide to solving the JavaScript heap out-of-memory error while running Jest.

It looked like another typical day, with different deployments. However, we were surprised by a CircleCI error while running some of our E2E test cases. After re-running the deployment process multiple times, we realized it began to fail randomly without any explanation. The test cases worked perfectly in our local environments, but this is what appeared on CircleCI:

Image showing how CircleCI failed while running the test cases.
CircleCI is failing while running the test cases.

After looking at the logs, we found a JavaScript heap out-of-memory error. Reached heap limit allocation failed? Why is this problem happening in CircleCI, and it didn’t happen in our local environments? Let’s try to understand and optimize this process!

CircleCI Error: JavaScript heap out of memory.
CircleCI Error: JavaScript heap out of memory.

This tutorial is going to be divided into the following points:

  1. Problem explanation.
  2. Solution 1: Change the NodeJS version.
  3. Solution 2: Using the Garbage Collector.
  4. CircleCI integration.

Problem explanation.

The heap size indicates the amount of memory allocated by the Node.js process during the test. We weren’t concerned about this problem until CircleCI complained about it, so we started doing some tests. Before looking at the problem, this is the configuration we had:

  • NodeJS (v16.17.1)
  • Typescript (ts-node v10.9.1)
  • Jest (ts-jest v27.1.5)
  • CircleCI

This is the command we used to run all the test cases of our Node application:

jest __tests__/e2e/ --logHeapUsage --runInBand --detectOpenHandles --forceExit

Just a few comments on this command:

  • The --logHeapUsage logs the heap…

--

--

Gonzalo Fernandez Plaza

Computer Science Engineer & Tech Lead 🖥️. Publishing AWS & Snowflake ❄️ courses & exams. https://www.fullcertified.com