Vitest MongoDB

1.0.3 · active · verified Wed Apr 22

vitest-mongodb is a utility package designed to facilitate integration testing for applications using MongoDB within a Vitest test environment. It leverages `mongodb-memory-server` to spin up an ephemeral, in-memory MongoDB instance for each test run or suite, ensuring isolated and clean test states without requiring a persistent MongoDB installation. The current stable version is 1.0.3, with updates typically driven by upstream changes in Vitest or `mongodb-memory-server`. This package does not have a stated fixed release cadence but follows standard semantic versioning practices. Its key differentiator from `jest-mongodb` is its native integration with Vitest's setup files and global variables, providing a streamlined, Vite-centric experience, although some configuration paradigms from `jest-mongodb` have different implementations or are not directly supported.

Common errors

Warnings

Install

Imports

Quickstart

This example configures Vitest to use `vitest-mongodb` via `setupFiles`, initializes and tears down an in-memory MongoDB server, and demonstrates how to connect and interact with it in a test using the globally exposed `__MONGO_URI__` variable. It also includes the necessary TypeScript declaration.

import { defineConfig } from "vitest/config";
import { afterAll, beforeAll } from "vitest";
import { setup, teardown } from "vitest-mongodb";
import { MongoClient } from "mongodb";
import { it, expect } from "vitest";

// vitest.config.ts
export default defineConfig({
  test: {
    setupFiles: ["./test/mongo-memory-server.ts"],
  },
});

// ./test/mongo-memory-server.ts
beforeAll(async () => {
  await setup({
    type: "default",
    serverOptions: { port: 27017, dbName: 'myTestDb' }
  });
});

afterAll(async () => {
  await teardown();
});

// ./test/global.d.ts (for TypeScript users)
declare var __MONGO_URI__: string;

// ./test/example.test.ts
it("should connect to the in-memory MongoDB and perform a ping", async () => {
  expect(globalThis.__MONGO_URI__).toBeDefined();
  const client = new MongoClient(globalThis.__MONGO_URI__);
  try {
    await client.connect();
    const db = client.db("myTestDb"); // Use the configured dbName
    const result = await db.command({ ping: 1 });
    expect(result.ok).toBe(1);
  } finally {
    await client.close();
  }
});

view raw JSON →