{"id":17400,"library":"vitest-mongodb","title":"Vitest MongoDB","description":"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.","status":"active","version":"1.0.3","language":"javascript","source_language":"en","source_url":"https://github.com/ec965/vitest-mongodb","tags":["javascript","vitest","vite","mongodb-memory-server","typescript"],"install":[{"cmd":"npm install vitest-mongodb","lang":"bash","label":"npm"},{"cmd":"yarn add vitest-mongodb","lang":"bash","label":"yarn"},{"cmd":"pnpm add vitest-mongodb","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides the in-memory MongoDB instance for testing.","package":"mongodb-memory-server","optional":false},{"reason":"The core test runner it integrates with; typically a devDependency in consumer projects, but fundamental to this library's function.","package":"vitest","optional":false}],"imports":[{"note":"vitest-mongodb is built for ESM; CommonJS `require` might work with bundlers but is not the idiomatic way to use it with Vitest.","wrong":"const { setup } = require('vitest-mongodb');","symbol":"setup","correct":"import { setup } from 'vitest-mongodb';"},{"note":"Used in Vitest's `afterAll` hook to clean up the in-memory MongoDB instance.","wrong":"const { teardown } = require('vitest-mongodb');","symbol":"teardown","correct":"import { teardown } from 'vitest-mongodb';"},{"note":"This is a global variable made available after `setup()` runs. For TypeScript, it requires a declaration like `declare var __MONGO_URI__: string;` in a `.d.ts` file.","symbol":"__MONGO_URI__","correct":"globalThis.__MONGO_URI__"}],"quickstart":{"code":"import { defineConfig } from \"vitest/config\";\nimport { afterAll, beforeAll } from \"vitest\";\nimport { setup, teardown } from \"vitest-mongodb\";\nimport { MongoClient } from \"mongodb\";\nimport { it, expect } from \"vitest\";\n\n// vitest.config.ts\nexport default defineConfig({\n  test: {\n    setupFiles: [\"./test/mongo-memory-server.ts\"],\n  },\n});\n\n// ./test/mongo-memory-server.ts\nbeforeAll(async () => {\n  await setup({\n    type: \"default\",\n    serverOptions: { port: 27017, dbName: 'myTestDb' }\n  });\n});\n\nafterAll(async () => {\n  await teardown();\n});\n\n// ./test/global.d.ts (for TypeScript users)\ndeclare var __MONGO_URI__: string;\n\n// ./test/example.test.ts\nit(\"should connect to the in-memory MongoDB and perform a ping\", async () => {\n  expect(globalThis.__MONGO_URI__).toBeDefined();\n  const client = new MongoClient(globalThis.__MONGO_URI__);\n  try {\n    await client.connect();\n    const db = client.db(\"myTestDb\"); // Use the configured dbName\n    const result = await db.command({ ping: 1 });\n    expect(result.ok).toBe(1);\n  } finally {\n    await client.close();\n  }\n});","lang":"typescript","description":"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."},"warnings":[{"fix":"To ensure a single shared MongoDB instance, run Vitest with the `--no-threads` option (e.g., `vitest --no-threads`).","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Create a declaration file (e.g., `test/global.d.ts`) with `declare var __MONGO_URI__: string;` to extend the `globalThis` interface.","message":"TypeScript users will encounter type errors when accessing `globalThis.__MONGO_URI__` because the type definition is not automatically inferred.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Directly access the MongoDB connection string via `globalThis.__MONGO_URI__` within your tests and setup files.","message":"The `jest-mongodb` option `mongoURLEnvName` is explicitly not implemented in `vitest-mongodb`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always specify `type: \"default\"` or `type: \"replSet\"` when passing `serverOptions` to the `setup` function, e.g., `await setup({ type: \"replSet\", serverOptions: { replSet: { count: 3 } } });`.","message":"Configuration options for `setup()` require a `type` property ('default' for `MongoMemoryServerOpts` or 'replSet' for `MongoMemoryReplSetOpts`) to correctly infer `serverOptions`.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Create a file like `test/global.d.ts` and add `declare var __MONGO_URI__: string;` to declare the global variable.","cause":"The TypeScript compiler does not have a type definition for the `__MONGO_URI__` global variable provided by `vitest-mongodb`.","error":"Property '__MONGO_URI__' does not exist on type 'typeof globalThis'. Did you mean 'GLOBAL_VAR_TEST_URI'?"},{"fix":"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`).","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.","error":"MongooseServerSelectionError: connect ECONNREFUSED ::1:xxxxx"},{"fix":"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).","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.","error":"TypeError: (0 , vitest_mongodb_1.setup) is not a function"}],"ecosystem":"npm","meta_description":null}