Best way to setup files for jest and mongodb

Viewed 181

Hihi. I'm having a problem where jest it's sometimes failing a couple of tests randomly, most of the time because of this error "mongodb memory server cannot perform operation: a background operation is currently running for collection".

In another post I read something about building differents mongo instance for each block of tests.

What I have so far is a globalsetup file where I start the mongo replica set like this:

// global.ts

import { MongoMemoryReplSet } from "mongodb-memory-server";

const replSet = new MongoMemoryReplSet({
  replSet: { storageEngine: "wiredTiger" },
});

module.exports = async () => {
  await replSet.waitUntilRunning();
  const uri = await replSet.getUri();
  process.env.MONGODB_URI = uri;
};

and my db.ts is like this

// db.ts
export const connect = async () => {
  mongoose.set("useFindAndModify", false); 
  const conn = mongoose.connect(
    process.env.MONGODB_URI || config.connectionString, connectionSettings
  );

When trying to call it from a test file I do something like this

// test.spec.ts
import db from "./db";
beforeAll(async () => {
  await db.connect();
});
afterAll(async (done) => {
  await db.dropCollections();
  await db.disconnect(done);
});

beforeEach(async () => {
  await seed();
});

describe('Some test', () => {
   it('Should not fail and get the seeders', () => {
      // some random tests using the seeds values
   })
})

What I read in that post is instead of using globalSetup use a setupFile that will run for every test instead of one globally and then I MIGHT be able to solve the concurrency issue I have with my tests.

So, to conclude, does anyone knows if there is a proper way to configure the mongodb in memory or if I am doing something THAT BAD that is allowing this to happend or if is there any kind of improvement I can do that will prevent "mongodb memory server cannot perform operation: a background operation is currently running for collection" this to happen?

0 Answers
Related