Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
2 changes: 2 additions & 0 deletions docs/guide/test-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
- [`vitest.cancelCurrentRun`](/api/advanced/vitest#cancelcurrentrun) was called programmatically
- Another test failed in parallel and the [`bail`](/config/bail) flag is set

Every [retry](/config/retry) and [repeat](/config/repeats) of a test gets a new signal.

```ts
it('stop request when test times out', async ({ signal }) => {
await fetch('/resource', { signal })
Expand Down
28 changes: 16 additions & 12 deletions packages/vitest/src/runtime/runner/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type {
} from './types'
import { manageArtifactAttachment, recordArtifact, recordAsyncOperation } from './artifact'
import { TaskDeadline } from './deadline'
import { PendingError } from './errors'
import { PendingError, TestRunAbortError } from './errors'
import { finishSendTasksUpdate } from './run'
import { getRunner } from './suite'

Expand Down Expand Up @@ -116,8 +116,9 @@ export function withTimeout<T extends (...args: any[]) => any>(
} as T
}

export function withCancel<T extends (...args: any[]) => any>(fn: T, signal: AbortSignal): T {
export function withCancel<T extends (...args: any[]) => any>(fn: T, context: TestContext): T {
return function runWithCancel(...args: T extends (...args: infer A) => any ? A : never) {
const signal = context.signal
return new Promise((resolve, reject) => {
const onAbort = () => reject(signal.reason)
signal.addEventListener('abort', onAbort, { once: true })
Expand Down Expand Up @@ -163,19 +164,22 @@ export function abortContextSignal(context: TestContext, error: Error): void {
abortController?.abort(error)
}

export function resetContextSignal(context: WriteableTestContext): void {
// the next attempt of a cancelled run starts aborted
if (abortControllers.get(context)?.signal.reason instanceof TestRunAbortError) {
return
}
const abortController = new AbortController()
abortControllers.set(context, abortController)
context.signal = abortController.signal
}

export function createTestContext(test: Test, runner: VitestRunner): TestContext {
const context = function () {
throw new Error('done() callback is deprecated, use promise instead')
} as unknown as WriteableTestContext

let abortController = abortControllers.get(context)

if (!abortController) {
abortController = new AbortController()
abortControllers.set(context, abortController)
}

context.signal = abortController.signal
resetContextSignal(context)
context.task = test

context.skip = (condition?: boolean | string, note?: string): never => {
Expand Down Expand Up @@ -237,7 +241,7 @@ export function createTestContext(test: Test, runner: VitestRunner): TestContext
timeout ?? runner.config.hookTimeout,
true,
new Error('STACK_TRACE_ERROR'),
(_, error) => abortController.abort(error),
(_, error) => abortContextSignal(context, error),
),
)
}
Expand All @@ -250,7 +254,7 @@ export function createTestContext(test: Test, runner: VitestRunner): TestContext
timeout ?? runner.config.hookTimeout,
true,
new Error('STACK_TRACE_ERROR'),
(_, error) => abortController.abort(error),
(_, error) => abortContextSignal(context, error),
),
)
}
Expand Down
5 changes: 4 additions & 1 deletion packages/vitest/src/runtime/runner/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import { getSafeTimers } from '@vitest/utils/timers'
import { limitConcurrency } from '../../utils/limit-concurrency'
import { hasFailed } from '../../utils/tasks'
import { collectTests } from './collect'
import { abortContextSignal } from './context'
import { abortContextSignal, resetContextSignal } from './context'
import {
AroundHookMultipleCallsError,
AroundHookSetupError,
Expand Down Expand Up @@ -621,6 +621,9 @@ async function runTest(test: Test, runner: VitestRunner): Promise<void> {
test.result.state = 'run' as TaskState
const retry = getRetryCount(test.retry)
for (let retryCount = 0; retryCount <= retry; retryCount++) {
if (retryCount > 0 || repeatCount > 0) {
resetContextSignal(test.context)
}
const attemptStart = now()
const attemptStartTime = unixNow()
const attemptErrorsStart = test.result.errors?.length ?? 0
Expand Down
5 changes: 1 addition & 4 deletions packages/vitest/src/runtime/runner/suite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,10 +415,7 @@ function createSuiteCollector(
setFn(
task,
withTimeout(
withCancel(
withAwaitAsyncAssertions(withFixtures(handler, { context }), task),
task.context.signal,
),
withCancel(withAwaitAsyncAssertions(withFixtures(handler, { context }), task), context),
timeout,
false,
stackTraceError,
Expand Down
63 changes: 63 additions & 0 deletions test/e2e/test/signal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,69 @@ test('timeout aborts all signals in concurrent tests', async () => {
})
})

test('every attempt after a timeout gets a new signal', async () => {
const { buildTree } = await runInlineTests({
'basic.test.ts': /* ts */ `
import { test } from 'vitest'
import { setTimeout } from 'node:timers/promises'
const retryDelays = [1000, 0]
test('retried', { retry: 1, timeout: 100 }, async ({ signal }) => {
await setTimeout(retryDelays.shift(), undefined, { signal })
})
const repeatDelays = [0, 1000, 0]
test('repeated', { repeats: 2, timeout: 100 }, async ({ signal }) => {
await setTimeout(repeatDelays.shift(), undefined, { signal })
})
`,
})
expect(buildTree(getAttempts)).toMatchInlineSnapshot(`
{
"basic.test.ts": {
"repeated": [
"passed",
[
"Test timed out in 100ms.
If this is a long-running test, pass a timeout value as the last argument or configure it globally with "testTimeout".",
],
"passed",
],
"retried": [
[
"Test timed out in 100ms.
If this is a long-running test, pass a timeout value as the last argument or configure it globally with "testTimeout".",
],
"passed",
],
},
}
`)
})

test('onTestFinished timeout aborts the signal of the current attempt', async () => {
const { results } = await runInlineTests({
'basic.test.ts': /* ts */ `
import { test } from 'vitest'
test('retried', { retry: 1 }, ({ signal, task, onTestFinished }) => {
signal.addEventListener('abort', () => {
task.meta.abortedAttempts ??= []
task.meta.abortedAttempts.push(task.result.retryCount)
})
onTestFinished(() => new Promise(() => {}), 50)
})
`,
})
expect(results[0].children.at(0)?.meta()).toEqual({
abortedAttempts: [0, 1],
})
})

function getAttempts(test: TestCase) {
return test.attempts().map((attempt) => attempt.errors?.map((error) => error.message) ?? 'passed')
}

class AbortReporter implements Reporter {
vitest!: Vitest
onInit(vitest: Vitest) {
Expand Down
Loading