Vitest MongoDB Memory Server Integration

0.2.7 · active · verified Tue Apr 21

vitest-mms (vitest-mongodb-memory-server) provides seamless integration of mongodb-memory-server with Vitest for efficient and isolated database testing. It allows developers to spin up an in-memory MongoDB instance for each test run or globally, ensuring a clean state. The library, currently at version 0.2.7, is in active development with frequent minor releases, indicating a rapid iteration cycle. Its key differentiators include pre-configured global setup hooks and dedicated test helpers (`setupDb`, `setupMongooseConnection`) for both the `mongodb` native driver and `mongoose` ODM, significantly reducing boilerplate. It also extends Vitest's test context, providing direct access to the `db` object or `mongoose` connection within test functions, simplifying interaction with the temporary database. This approach helps maintain test isolation and speeds up test execution compared to relying on external database instances.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates the global Vitest setup using `vitest-mms/globalSetup` and how to inject the `MONGO_URI` into tests for manual connection with the native MongoDB driver.

import { defineConfig } from 'vitest/config';
import { inject, test, expect } from 'vitest';
import { MongoClient } from 'mongodb';

// vitest.config.mjs (or .ts)
export default defineConfig({
  test: {
    globalSetup: ['./vitest.globalSetup.ts'], // or vitest-mms/globalSetup directly
  },
});

// vitest.globalSetup.ts
import 'vitest-mms/globalSetup';

// index.test.ts
const MONGO_URI = inject<string>('MONGO_URI');

test('should connect to in-memory MongoDB', async () => {
  expect(MONGO_URI).toBeTypeOf('string');
  expect(MONGO_URI).toMatch(/^mongodb:\/\/127\.0\.0\.1:\d+\//);

  const client = new MongoClient(MONGO_URI);
  await client.connect();
  const db = client.db('testdb');
  const collection = db.collection('testcollection');
  await collection.insertOne({ name: 'Test Document' });
  const doc = await collection.findOne({ name: 'Test Document' });
  expect(doc).toBeDefined();
  await client.close();
});

view raw JSON →