Skip to content

docs(guides): add vitest integration example #937

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 25, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions docs/guides/integration-examples/test-runners.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,83 @@ 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

<span class="badge badge--secondary">vitest version 3</span>

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';
import { MongoMemoryServer } from 'mongodb-memory-server';

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');
});
```

:::note
Keep in mind that the global setup is running in a different global scope, so your tests don't have access to variables defined here. However, you can pass down serializable data to tests via [provide](https://vitest.dev/config/#provide) method as described above.
:::

See also [vitest-mms](https://github.com/danielpza/vitest-mms), which provides the `globalSetup` configuration among others helpers:

```ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
test: {
globalSetup: ['vitest-mms/globalSetup'],
},
});
```