mongodb-memory-server: How to clear used memory between test suites? (possible memory leak)

Versions

  • NodeJS: 18.16.1
  • mongodb-memory-server-*: 6.3.3
  • mongodb(the binary version): 4.4.13
  • mongoose: 5.9.4
  • system: Linux, Ubuntu 23.04

package: mongo-memory-server

What is your question?

Hello, I’m using jest to perform integration tests and I have a lot of suites that were running smoothly. But as the number of suites increased, a considerable increase in memory usage was noticed, to the point that it is impossible to run the tests. (The image below shows the heap usage after some time testing)

MicrosoftTeams-image (2)

Doing a bit of debugging, using node --inspect-brk --expose-gc ./node_modules/.bin/jest --runInBand --logHeapUsage and taking a snapshot of the heap with the chromium inspection tool, you can see that there are several “lost” BSON objects in memory, which for some reason are referenced when moving from one test suite to another.

MicrosoftTeams-image (1)

My jest configuration follows a single file setup present in this template:

let mongoServer

beforeAll(async () => {
  mongoServer = new MongodbMemoryServer()
  const mongoUri = await mongoServer.getUri()
  mongoose.connect(mongoUri, undefined, (err) => {
    if (err) console.error(err)
  })
})

afterAll(async () => {
  await mongoose.disconnect()
  await mongoServer.stop()
})

afterEach(async () => {
  const { collections } = mongoose.connection
  const promises = []
  Object.keys(collections).forEach((collection) => {
    promises.push(collections[collection].deleteMany({}))
  })
  await Promise.all(promises)
})

I already saw the recommended settings for jest present in the documentation of this library, but there a single instance of mongo-memory-server is created for all suites, while in the code of this template a new one is created for each test suite and I would like to keep it that way.

My question is if you or someone who has had this problem could help me to find out why these objects are getting referenced between one test suite and another, preventing them from being cleared from memory, and how to solve it.

Thanks in advance for any help

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 23

Most upvoted comments

beta 9.0.0-beta.1 has been released, which has the replacement for get-port, which hopefully has less leakage