mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
15.97k stars 519 forks source link

Memory Leak while running e2e test. #2289

Closed aq1018 closed 2 months ago

aq1018 commented 2 months ago

Prerequisites

Environment check

Node.js version

v22.8.0

Reproduction repository

https://github.com/think-life/msw-memory-leak

Reproduction steps

Positive Test

  1. clone the reproduction repository
  2. run npm install
  3. run node --expose-gc --no-compilation-cache ./node_modules/.bin/jest --silent --runInBand --detectOpenHandles --logHeapUsage

You will see something like:

 PASS  test/e2e/i.spec.ts (201 MB heap size)
 PASS  test/e2e/a.spec.ts (214 MB heap size)
 PASS  test/e2e/h.spec.ts (224 MB heap size)
 PASS  test/e2e/d.spec.ts (233 MB heap size)
 PASS  test/e2e/k.spec.ts (243 MB heap size)
 PASS  test/e2e/f.spec.ts (253 MB heap size)
 PASS  test/e2e/l.spec.ts (262 MB heap size)
 PASS  test/e2e/c.spec.ts (272 MB heap size)
 PASS  test/e2e/j.spec.ts (282 MB heap size)
 PASS  test/e2e/e.spec.ts (291 MB heap size)
 PASS  test/e2e/b.spec.ts (301 MB heap size)
 PASS  test/e2e/g.spec.ts (310 MB heap size)

Notice the heap size keeps increasing.

Note, I added global.gc() in afterAll so that GC is run at the end of each test suite.

Negative Test

  1. Edit the package.json file, and change the msw version number to 2.4.3.
  2. Run npm install
  3. Run node --expose-gc --no-compilation-cache ./node_modules/.bin/jest --silent --runInBand --detectOpenHandles --logHeapUsage

You will see something like this:

 PASS  test/e2e/i.spec.ts (205 MB heap size)
 PASS  test/e2e/h.spec.ts (218 MB heap size)
 PASS  test/e2e/d.spec.ts (218 MB heap size)
 PASS  test/e2e/f.spec.ts (218 MB heap size)
 PASS  test/e2e/k.spec.ts (219 MB heap size)
 PASS  test/e2e/j.spec.ts (219 MB heap size)
 PASS  test/e2e/e.spec.ts (219 MB heap size)
 PASS  test/e2e/l.spec.ts (219 MB heap size)
 PASS  test/e2e/c.spec.ts (220 MB heap size)
 PASS  test/e2e/a.spec.ts (220 MB heap size)
 PASS  test/e2e/g.spec.ts (220 MB heap size)
 PASS  test/e2e/b.spec.ts (220 MB heap size)

Although it is still increasing in size, the magnitude is much smaller.

Current behavior

Memory usage keep increasing. It seems the interaction between @msw/interceptors, supertest, and nestjs server is causing memory not being GC'ed properly.

Expected behavior

Memory usage should be relatively stable.

kettanaito commented 2 months ago

Hi, @aq1018. Thanks for reporting this!

Can you please try this in Vite? We are not addressing Jest-related issues (see this). Until we can confirm this is happening in modern test runners, I will close the issue.

aq1018 commented 2 months ago

Hi @kettanaito,

I create a new branch on my test repo to use vitest, and it does not leak memory.

I'm sold on vitest.