First of all, make sure that you have leaky tests by running jest with the option:
jest --logHeapUsage
Run your tests and check that the memory consumption is increasing over time, like this (file names changed):
PASS __tests__/pages/file.test.tsx (181 MB heap size)
PASS __tests__/pages/file2.test.tsx (193 MB heap size)
PASS __tests__/components/Header/file3.test.tsx (201 MB heap size)
PASS __tests__/components/Header/file4.test.tsx (192 MB heap size)
PASS __tests__/components/Header/file5.test.tsx (218 MB heap size)
PASS __tests__/pages/file6.test.tsx (201 MB heap size)
PASS __tests__/components/file6.test.tsx (203 MB heap size)
PASS __tests__/components/file7.test.tsx (213 MB heap size)
PASS __tests__/components/file8.test.tsx (234 MB heap size)
PASS __tests__/components/file9.test.tsx (222 MB heap size)
PASS __tests__/components/file10.test.tsx (240 MB heap size)
PASS __tests__/components/file11.test.tsx (231 MB heap size)
PASS __tests__/utils/file12.test.tsx (239 MB heap size)
PASS __tests__/components/file13.test.tsx (251 MB heap size)
PASS __tests__/components/file14.test.tsx (239 MB heap size)
PASS __tests__/components/file15.test.tsx (249 MB heap size)
PASS __tests__/components/file16.test.tsx (143 MB heap size)
To fix this, change your npm run test
or yarn test
command in your package.json
to:
node --expose-gc ./node_modules/.bin/jest --runInBand --logHeapUsage
Run the command. Here's my output:
PASS __tests__/components/file.test.tsx (143 MB heap size)
PASS __tests__/pages/onboarding/file1.test.tsx (149 MB heap size)
PASS __tests__/components/file2.test.tsx (146 MB heap size)
PASS __tests__/components/file3.test.tsx (146 MB heap size)
PASS __tests__/components/file4.test.tsx (153 MB heap size)
PASS __tests__/components/Header /file5.test.tsx (149 MB heap size)
PASS __tests__/pages/file6.test.tsx (149 MB heap size)
PASS __tests__/pages/file7.test.tsx (149 MB heap size)
PASS __tests__/components/file8.test.tsx (147 MB heap size)
PASS __tests__/components/file9.test.tsx (148 MB heap size)
PASS __tests__/pages/file10.test.tsx (148 MB heap size)
PASS __tests__/components/Header /file11.test.tsx (148 MB heap size)
PASS __tests__/functions/file12.test.tsx (149 MB heap size)
PASS __tests__/components/file13.test.tsx (148 MB heap size)
PASS __tests__/components/file14.test.tsx (150 MB heap size)
PASS __tests__/components/file15.test.tsx (150 MB heap size)
PASS __tests__/components/Header /file16.test.tsx (149 MB heap size)
PASS __tests__/components/file17.test.tsx (149 MB heap size)
PASS __tests__/utils/file18.test.tsx (150 MB heap size)
PASS __tests__/components/file19.test.tsx (149 MB heap size)
PASS __tests__/pages/file20.test.tsx (150 MB heap size)
As you can see, the memory consumption is much more consistent.
You can read more about this issue and the solution in this Github issue, which describes a leaky garbage collector issue with jest.