shelfio / jest-mongodb

Jest preset for MongoDB in-memory server

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Blank DB for every single test

PzYon opened this issue · comments

I would like to have a clean DB for every single unit test.

I'm using more or less the code from your README. However I'm using beforeEach and afterEach instead of *All. I would have expected the database to be clear after closing the connection in one unit test and creating a new one in the next, but apparently this is not the case.

When rerunning the tests, the first test always starts from a "clean" database. How can I achieve this for every test? At the moment, to achieve what I want, I drop the tables in afterEach, but I'm sure there must be a better approach? You can view me code here.

I have the same issue. Why not having a separate database for each test suites (with a auto generated name) ? This kind of setup has worked well for me in the past.

I clean db collections in beforeEach as well. There were a couple of reasons behind keeping current behavior.

Changing default behavior to clean everything before each test doesn't leave a chance to preserve documents between tests if users wish so. If you want to have a clean state, it's a matter of 1 line of code: await db.collection('name').deleteMany({})

But I'm not against this approach by any means, so PRs are welcome:) Meanwhile, I'll add some explanations to the README

I can open a separate issue for this, but when running tests in parallel with asynchronous code, cleaning the db in beforeEach does not work.

I agree and @aymericbouzy I have the same issue. Any ideas on how to fix it?

What I do in my own setup (not using this package) is using a fresh db in each test suite. I have something along these lines in my setup file :

beforeAll(async () => {
  await connect(
    `mongodb://localhost:27017/test_${randomToken()}`
  )
})

afterEach(async () => {
  await clear()
})

afterAll(async () => {
  await disconnect()
})
commented

Same issue, I moved to mongodb-memory-server and everything works fine.

const startDB = () => new Promise((resolve) => {
  const mongoServer = new MongoMemoryServer();
  mongoServer
    .getConnectionString()
    .then(mongoUri => resolve({
      mongoServer,
      db: MongoDB.connect(mongoUri),
    }));
});