Skip to content
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

feat(vitest): add onTestsRerun method to global setup context #6803

Merged
merged 4 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat(vitest): add onWatcherRerun method to global setup context
  • Loading branch information
sheremet-va committed Nov 5, 2024
commit 19cfa88e2b36d8c5e75fb95f49df052f2ca46d6a
12 changes: 12 additions & 0 deletions docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,18 @@ inject('wsPort') === 3000
```
:::

Since Vitest 2.2.0, you can define a custom callback function to be called when Vitest reruns tests. If the function is asynchronous, the runner will wait for it to complete before executing the tests.

```ts
import type { GlobalSetupContext } from 'vitest/node'

export default function setup({ onWatcherRerun }: GlobalSetupContext) {
onWatcherRerun(async () => {
await restartDb()
})
}
```

### forceRerunTriggers<NonProjectOption />

- **Type**: `string[]`
Expand Down
18 changes: 15 additions & 3 deletions packages/vitest/src/node/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Writable } from 'node:stream'
import type { ViteDevServer } from 'vite'
import type { defineWorkspace } from 'vitest/config'
import type { SerializedCoverageConfig } from '../runtime/config'
import type { ArgumentsType, OnServerRestartHandler, ProvidedContext, UserConsoleLog } from '../types/general'
import type { ArgumentsType, OnServerRestartHandler, OnWatcherRerunHandler, ProvidedContext, UserConsoleLog } from '../types/general'
import type { ProcessPool, WorkspaceSpec } from './pool'
import type { TestSpecification } from './spec'
import type { ResolvedConfig, UserConfig, VitestRunMode } from './types/config'
Expand Down Expand Up @@ -102,6 +102,7 @@ export class Vitest {
private _onClose: (() => Awaited<unknown>)[] = []
private _onSetServer: OnServerRestartHandler[] = []
private _onCancelListeners: ((reason: CancelReason) => Promise<void> | void)[] = []
private _onUserWatcherRerun: OnWatcherRerunHandler[] = []

async setServer(options: UserConfig, server: ViteDevServer, cliOptions: UserConfig) {
this.unregisterWatcher?.()
Expand All @@ -113,6 +114,7 @@ export class Vitest {
this.coverageProvider = undefined
this.runningPromise = undefined
this._cachedSpecs.clear()
this._onUserWatcherRerun = []

const resolved = resolveConfig(this.mode, options, server.config, this.logger)

Expand Down Expand Up @@ -691,7 +693,10 @@ export class Vitest {
files = files.filter(file => filteredFiles.some(f => f[1] === file))
}

await this.report('onWatcherRerun', files, trigger)
await Promise.all([
this.report('onWatcherRerun', files, trigger),
...this._onUserWatcherRerun.map(fn => fn(files)),
])
await this.runFiles(files.flatMap(file => this.getProjectsByTestFile(file)), allTestsRun)

await this.report('onWatcherStart', this.state.getFiles(files))
Expand Down Expand Up @@ -813,7 +818,10 @@ export class Vitest {

const triggerIds = new Set(triggerId.map(id => relative(this.config.root, id)))
const triggerLabel = Array.from(triggerIds).join(', ')
await this.report('onWatcherRerun', files, triggerLabel)
await Promise.all([
this.report('onWatcherRerun', files, triggerLabel),
...this._onUserWatcherRerun.map(fn => fn(files)),
])

await this.runFiles(files.flatMap(file => this.getProjectsByTestFile(file)), false)

Expand Down Expand Up @@ -1150,4 +1158,8 @@ export class Vitest {
onClose(fn: () => void) {
this._onClose.push(fn)
}

onWatcherRerun(fn: OnWatcherRerunHandler): void {
this._onUserWatcherRerun.push(fn)
}
}
3 changes: 2 additions & 1 deletion packages/vitest/src/node/globalSetup.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ViteNodeRunner } from 'vite-node/client'
import type { ProvidedContext } from '../types/general'
import type { OnWatcherRerunHandler, ProvidedContext } from '../types/general'
import type { ResolvedConfig } from './types/config'
import { toArray } from '@vitest/utils'

Expand All @@ -9,6 +9,7 @@ export interface GlobalSetupContext {
key: T,
value: ProvidedContext[T]
) => void
onWatcherRerun: (cb: OnWatcherRerunHandler) => void
}

export interface GlobalSetupFile {
Expand Down
1 change: 1 addition & 0 deletions packages/vitest/src/node/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ export class WorkspaceProject {
const teardown = await globalSetupFile.setup?.({
provide: (key, value) => this.provide(key, value),
config: this.config,
onWatcherRerun: cb => this.ctx.onWatcherRerun(cb),
})
if (teardown == null || !!globalSetupFile.teardown) {
continue
Expand Down
5 changes: 4 additions & 1 deletion packages/vitest/src/public/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,10 @@ export type {
TscErrorInfo as TypeCheckErrorInfo,
} from '../typecheck/types'

export type { OnServerRestartHandler } from '../types/general'
export type {
OnServerRestartHandler,
OnWatcherRerunHandler,
} from '../types/general'

export { createDebugger } from '../utils/debugger'

Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/types/general.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,5 @@ export interface ModuleGraphData {
}

export type OnServerRestartHandler = (reason?: string) => Promise<void> | void

export type OnWatcherRerunHandler = (testFiles: string[]) => Promise<void> | void
export interface ProvidedContext {}