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.
npm install vitest-mongodbVerified import paths — ran on the pinned version, not inferred.
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.
To ensure a single shared MongoDB instance, run Vitest with the `--no-threads` option (e.g., `vitest --no-threads`).
Create a declaration file (e.g., `test/global.d.ts`) with `declare var __MONGO_URI__: string;` to extend the `globalThis` interface.
Directly access the MongoDB connection string via `globalThis.__MONGO_URI__` within your tests and setup files.
Always specify `type: "default"` or `type: "replSet"` when passing `serverOptions` to the `setup` function, e.g., `await setup({ type: "replSet", serverOptions: { replSet: { count: 3 } } });`.Create a file like `test/global.d.ts` and add `declare var __MONGO_URI__: string;` to declare the global variable.
Ensure `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`).
Verify 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).