Vitest MongoDB
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
-
Property '__MONGO_URI__' does not exist on type 'typeof globalThis'. Did you mean 'GLOBAL_VAR_TEST_URI'?
cause The TypeScript compiler does not have a type definition for the `__MONGO_URI__` global variable provided by `vitest-mongodb`.fixCreate a file like `test/global.d.ts` and add `declare var __MONGO_URI__: string;` to declare the global variable. -
MongooseServerSelectionError: connect ECONNREFUSED ::1:xxxxx
cause The in-memory MongoDB server failed to start, or tests are trying to connect before it's ready, often due to Vitest running tests in separate threads without `vitest-mongodb`'s setup being correctly executed once.fixEnsure `vitest.config.ts` includes `setupFiles` pointing to your `vitest-mongodb` setup. If running tests concurrently, add `--no-threads` to your Vitest command (e.g., `vitest --no-threads`). -
TypeError: (0 , vitest_mongodb_1.setup) is not a function
cause This error typically indicates an incorrect import statement, often when trying to use CommonJS `require` syntax in an ESM project, or a bundler misconfiguration.fixVerify that you are using ESM `import { setup, teardown } from 'vitest-mongodb';` and that your Vitest project is correctly configured for ESM modules (e.g., `type: "module"` in `package.json` or appropriate `tsconfig.json` settings).
Warnings
- gotcha When running Vitest tests concurrently with worker threads, `vitest-mongodb`'s setup file might be called multiple times, leading to multiple MongoDB instances and inconsistent test states.
- gotcha TypeScript users will encounter type errors when accessing `globalThis.__MONGO_URI__` because the type definition is not automatically inferred.
- gotcha The `jest-mongodb` option `mongoURLEnvName` is explicitly not implemented in `vitest-mongodb`.
- gotcha Configuration options for `setup()` require a `type` property ('default' for `MongoMemoryServerOpts` or 'replSet' for `MongoMemoryReplSetOpts`) to correctly infer `serverOptions`.
Install
-
npm install vitest-mongodb -
yarn add vitest-mongodb -
pnpm add vitest-mongodb
Imports
- setup
const { setup } = require('vitest-mongodb');import { setup } from 'vitest-mongodb'; - teardown
const { teardown } = require('vitest-mongodb');import { teardown } from 'vitest-mongodb'; - __MONGO_URI__
globalThis.__MONGO_URI__
Quickstart
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();
}
});