Jest memory leak issue

Viewed 245

I am running jest unit and integrations tests on my NodeJS api, I am facing some issue with possible memory leak. I tried upgrading Jest from 26.3.2 to 27.5.1, but that did not help much. I took some heap snapshot from chrome console.

Snapshot 1 enter image description here

Snapshot 2

Snapshot 3 enter image description here

Snapshot 4

enter image description here

From above snapshot I can see that the increase in usage is going very high. But I am unable to understand what's going on wrong.

I see something's up with String, Object and JSBufferData. But not sure what the issue is.

In case of string, I see this: enter image description here

Multiple calls/lines for the stringified version of library, but where this comes from and why?

In case of Object:

enter image description here

The object in screenshot is possibly coming from a library I use countries-list this is to get list of countries to find ISO name.

And finally the JSBufferData, which points to something like URLSearchParam, but I am not using anywhere in my application any of the above object/library: enter image description here

Stack I use:

NodeJS: 16.14.2 Jest: 27.5.1 jest-searial-runner: 1.2.0

1 Answers

You can try to use --logHeapUsage
From documentation:

Logs the heap usage after every test. Useful to debug memory leaks. Use together with --runInBand and --expose-gc in node.

You can try exposing the garbage collector with --expose-gc and adding

afterAll(() => {
  global.gc && global.gc()
})

Another option is jest -w 1 to avoid these memory issues.

--maxWorkers
Alias: -w. Specifies the maximum number of workers the worker-pool will spawn for running tests. In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In watch mode, this defaults to half of the available cores on your machine to ensure Jest is unobtrusive and does not grind your machine to a halt. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases.
For environments with variable CPUs available, you can use percentage based configuration: --maxWorkers=50%

References:
Cannot find memory leak in my Express.js Jest tests
My Jests tests are leaking memory, how can I fix this?
What are the steps to follow to debug memory leak in Jest?
https://chanind.github.io/javascript/2019/10/12/jest-tests-memory-leak.html

Related