diff --git a/docs/guides/integration-examples/test-runners.md b/docs/guides/integration-examples/test-runners.md index 2f1bddf70..4dd9db9e5 100644 --- a/docs/guides/integration-examples/test-runners.md +++ b/docs/guides/integration-examples/test-runners.md @@ -142,3 +142,66 @@ For AVA there is a [detailed written tutorial](https://github.com/zellwk/ava/blo :::note Note that this tutorial is pre mongodb-memory-server 7.x. ::: + +## vitest + +For [vitest](https://vitest.dev/), create a [global setup file](https://vitest.dev/config/#globalsetup). + +`vitest.config.mts`: + +```ts +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + globalSetup: ['./globalSetup.ts'], + }, +}); +``` + +`globalSetup.ts`: + +```ts +import type { TestProject } from 'vitest/node'; + +declare module 'vitest' { + export interface ProvidedContext { + MONGO_URI: string; + } +} + +export default async function setup({ provide }: TestProject) { + const mongod = await MongoMemoryServer.create(); + + const uri = mongod.getUri(); + + provide('MONGO_URI', uri); + + return async () => { + await mongod.stop(); + }; +} +``` + +Then use it in your tests: + +`example.test.js` + +```ts +import { inject, test } from 'vitest'; +import { MongoClient } from 'mongodb'; + +const MONGO_URI = inject('MONGO_URI'); +const mongoClient = new MongoClient(MONGO_URI); + +beforeAll(async () => { + await mongoClient.connect(); + return () => mongoClient.disconnect(); +}); + +test('...', () => { + const db = mongoClient.db('my-db'); +}); +``` + +See also [vitest-mms](https://github.com/danielpza/vitest-mms)