Skip to content

Commit fb955e6

Browse files
committed
Merge branch 'master' into beta
2 parents 9f007a8 + 6412476 commit fb955e6

File tree

1 file changed

+75
-3
lines changed

1 file changed

+75
-3
lines changed

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

Lines changed: 75 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,10 +135,82 @@ describe('...', () => {
135135
});
136136
```
137137

138-
## AVA test runner
138+
## vitest
139139

140-
For AVA there is a [detailed written tutorial](https://github.com/zellwk/ava/blob/8b7ccba1d80258b272ae7cae6ba4967cd1c13030/docs/recipes/endpoint-testing-with-mongoose.md) on how to test mongoose models with mongodb-memory-server by [@zellwk](https://github.com/zellwk).
140+
<span class="badge badge--secondary">vitest version 3</span>
141+
142+
For [vitest](https://vitest.dev/), create a [global setup file](https://vitest.dev/config/#globalsetup).
143+
144+
`vitest.config.mts`:
145+
146+
```ts
147+
import { defineConfig } from 'vitest/config';
148+
149+
export default defineConfig({
150+
test: {
151+
globalSetup: ['./globalSetup.ts'],
152+
},
153+
});
154+
```
155+
156+
`globalSetup.ts`:
157+
158+
```ts
159+
import type { TestProject } from 'vitest/node';
160+
import { MongoMemoryServer } from 'mongodb-memory-server';
161+
162+
declare module 'vitest' {
163+
export interface ProvidedContext {
164+
MONGO_URI: string;
165+
}
166+
}
167+
168+
export default async function setup({ provide }: TestProject) {
169+
const mongod = await MongoMemoryServer.create();
170+
171+
const uri = mongod.getUri();
172+
173+
provide('MONGO_URI', uri);
174+
175+
return async () => {
176+
await mongod.stop();
177+
};
178+
}
179+
```
180+
181+
Then use it in your tests:
182+
183+
`example.test.js`
184+
185+
```ts
186+
import { inject, test } from 'vitest';
187+
import { MongoClient } from 'mongodb';
188+
189+
const MONGO_URI = inject('MONGO_URI');
190+
const mongoClient = new MongoClient(MONGO_URI);
191+
192+
beforeAll(async () => {
193+
await mongoClient.connect();
194+
return () => mongoClient.disconnect();
195+
});
196+
197+
test('...', () => {
198+
const db = mongoClient.db('my-db');
199+
});
200+
```
141201

142202
:::note
143-
Note that this tutorial is pre mongodb-memory-server 7.x.
203+
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.
144204
:::
205+
206+
See also [vitest-mms](https://github.com/danielpza/vitest-mms), which provides the `globalSetup` configuration among others helpers:
207+
208+
```ts
209+
import { defineConfig } from 'vitest/config';
210+
211+
export default defineConfig({
212+
test: {
213+
globalSetup: ['vitest-mms/globalSetup'],
214+
},
215+
});
216+
```

0 commit comments

Comments
 (0)