Skip to content

Commit

Permalink
docs: improve "provide" documentation (#5554)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Apr 16, 2024
1 parent c84113f commit f2066c4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 12 deletions.
25 changes: 14 additions & 11 deletions docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -974,29 +974,32 @@ Since Vitest 1.0.0-beta, global setup runs only if there is at least one running

Beware that the global setup is running in a different global scope, so your tests don't have access to variables defined here. However, since 1.0.0 you can pass down serializable data to tests via `provide` method:

```ts
// globalSetup.js
:::code-group
```js [globalSetup.js]
export default function setup({ provide }) {
provide('wsPort', 3000)
}
```
```ts [globalSetup.ts]
import type { GlobalSetupContext } from 'vitest/node'

```ts
// example.test.js
import { inject } from 'vitest'

inject('wsPort') === 3000
```

If you are using TypeScript, you can extend `ProvidedContext` type to have type safe access to `provide/inject` methods:
export default function setup({ provide }: GlobalSetupContext) {
provide('wsPort', 3000)
}

```ts
// You can also extend `ProvidedContext` type
// to have type safe access to `provide/inject` methods:
declare module 'vitest' {
export interface ProvidedContext {
wsPort: number
}
}
```
```ts [example.test.js]
import { inject } from 'vitest'

inject('wsPort') === 3000
```
:::

### watchExclude<NonProjectOption />
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/node/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export class WorkspaceProject {
return this.ctx.getCoreWorkspaceProject() === this
}

provide = (key: string, value: unknown) => {
provide = <T extends keyof ProvidedContext>(key: T, value: ProvidedContext[T]) => {
try {
structuredClone(value)
}
Expand Down

0 comments on commit f2066c4

Please sign in to comment.