Skip to content

Commit bcc6e02

Browse files
authored
docs(test-runners): add vitest integration example (#937)
* docs(guides): add vitest integration example * update based on code review * add note * add missing import
1 parent e4992fd commit bcc6e02

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

docs/guides/integration-examples/test-runners.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,3 +142,83 @@ For AVA there is a [detailed written tutorial](https://github.com/zellwk/ava/blo
142142
:::note
143143
Note that this tutorial is pre mongodb-memory-server 7.x.
144144
:::
145+
146+
## vitest
147+
148+
<span class="badge badge--secondary">vitest version 3</span>
149+
150+
For [vitest](https://vitest.dev/), create a [global setup file](https://vitest.dev/config/#globalsetup).
151+
152+
`vitest.config.mts`:
153+
154+
```ts
155+
import { defineConfig } from 'vitest/config';
156+
157+
export default defineConfig({
158+
test: {
159+
globalSetup: ['./globalSetup.ts'],
160+
},
161+
});
162+
```
163+
164+
`globalSetup.ts`:
165+
166+
```ts
167+
import type { TestProject } from 'vitest/node';
168+
import { MongoMemoryServer } from 'mongodb-memory-server';
169+
170+
declare module 'vitest' {
171+
export interface ProvidedContext {
172+
MONGO_URI: string;
173+
}
174+
}
175+
176+
export default async function setup({ provide }: TestProject) {
177+
const mongod = await MongoMemoryServer.create();
178+
179+
const uri = mongod.getUri();
180+
181+
provide('MONGO_URI', uri);
182+
183+
return async () => {
184+
await mongod.stop();
185+
};
186+
}
187+
```
188+
189+
Then use it in your tests:
190+
191+
`example.test.js`
192+
193+
```ts
194+
import { inject, test } from 'vitest';
195+
import { MongoClient } from 'mongodb';
196+
197+
const MONGO_URI = inject('MONGO_URI');
198+
const mongoClient = new MongoClient(MONGO_URI);
199+
200+
beforeAll(async () => {
201+
await mongoClient.connect();
202+
return () => mongoClient.disconnect();
203+
});
204+
205+
test('...', () => {
206+
const db = mongoClient.db('my-db');
207+
});
208+
```
209+
210+
:::note
211+
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.
212+
:::
213+
214+
See also [vitest-mms](https://github.com/danielpza/vitest-mms), which provides the `globalSetup` configuration among others helpers:
215+
216+
```ts
217+
import { defineConfig } from 'vitest/config';
218+
219+
export default defineConfig({
220+
test: {
221+
globalSetup: ['vitest-mms/globalSetup'],
222+
},
223+
});
224+
```

0 commit comments

Comments
 (0)