You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/guide/test-context.md
+40Lines changed: 40 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -373,6 +373,46 @@ describe('another type of schema', () => {
373
373
})
374
374
```
375
375
376
+
#### Per-Scope Context <Version>3.2.0</Version>
377
+
378
+
You can define context that will be initiated once per file or a worker. It is initiated the same way as a regular fixture with an objects parameter:
379
+
380
+
```ts
381
+
import { test asbaseTest } from'vitest'
382
+
383
+
exportconsttest=baseTest.extend({
384
+
perFile: [
385
+
({}, { use }) =>use([]),
386
+
{ scope: 'file' },
387
+
],
388
+
perWorker: [
389
+
({}, { use }) =>use([]),
390
+
{ scope: 'worker' },
391
+
],
392
+
})
393
+
```
394
+
395
+
The value is initialised the first time any test has accessed it, unless the fixture options have `auto: true` - in this case the value is initialised before any test has run.
396
+
397
+
```ts
398
+
consttest=baseTest.extend({
399
+
perFile: [
400
+
({}, { use }) =>use([]),
401
+
{
402
+
scope: 'file',
403
+
// always run this hook before any test
404
+
auto: true
405
+
},
406
+
],
407
+
})
408
+
```
409
+
410
+
The `worker` scope will run the fixture once per worker. The number of running workers depends on various factors. By default, every file runs in a separate worker, so `file` and `worker` scopes work the same way.
411
+
412
+
However, if you disable [isolation](/config/#isolate), then the number of workers is limited by the [`maxWorkers`](/config/#maxworkers) or [`poolOptions`](/config/#pooloptions) configuration.
413
+
414
+
Note that specifying `scope: 'worker'` when running tests in `vmThreads` or `vmForks` will work the same way as `scope: 'file'`. This limitation exists because every test file has its own VM context, so if Vitest were to initiate it once, one context could leak to another and create many reference inconsistencies (instances of the same class would reference different constructors, for example).
415
+
376
416
#### TypeScript
377
417
378
418
To provide fixture types for all your custom contexts, you can pass the fixtures type as a generic.
thrownewTypeError('[@vitest/runner] The worker context is not available in the current test runner. Please, provide the `getWorkerContext` method when initiating the runner.')
0 commit comments