From 2dff73912a23fe1f3d0a225281ed85734d6c4ac2 Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa <4232207+hi-ogawa@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:23:34 +0900 Subject: [PATCH 1/9] feat: attribute console logs to test attempts Co-Authored-By: Claude Opus 5.5 --- docs/api/advanced/test-case.md | 2 + packages/browser/src/client/tester/logger.ts | 6 +- packages/vitest/src/public/browser.ts | 1 + packages/vitest/src/runtime/console.ts | 90 +++++++++------ packages/vitest/src/runtime/runner/run.ts | 3 +- .../vitest/src/runtime/runner/test-state.ts | 17 ++- packages/vitest/src/types/general.ts | 4 + test/browser/specs/runner.test.ts | 51 ++++++++- test/e2e/test/console.test.ts | 103 ++++++++++++++++++ 9 files changed, 238 insertions(+), 39 deletions(-) diff --git a/docs/api/advanced/test-case.md b/docs/api/advanced/test-case.md index c07e47fb631c..692de867d2ec 100644 --- a/docs/api/advanced/test-case.md +++ b/docs/api/advanced/test-case.md @@ -361,3 +361,5 @@ function logs(): ReadonlyArray ``` Console logs recorded during the test execution. + +Each log printed during an attempt has the `retryIndex` and `repeatIndex` of that attempt, so it can be matched with an entry of [`attempts()`](#attempts). diff --git a/packages/browser/src/client/tester/logger.ts b/packages/browser/src/client/tester/logger.ts index 30961bea362a..4fe2fc7aae26 100644 --- a/packages/browser/src/client/tester/logger.ts +++ b/packages/browser/src/client/tester/logger.ts @@ -1,4 +1,4 @@ -import { format } from 'vitest/internal/browser' +import { format, getCurrentAttempt } from 'vitest/internal/browser' import { getConfig } from '../utils' import { rpc } from './rpc' import { getBrowserRunner } from './runner' @@ -122,7 +122,8 @@ function sendLog(type: 'stdout' | 'stderr', content: string, disableStack?: bool } const unknownTestId = '__vitest__unknown_test__' // @ts-expect-error untyped global - const taskId = globalThis.__vitest_worker__?.current?.id ?? unknownTestId + const task = globalThis.__vitest_worker__?.current + const taskId = task?.id ?? unknownTestId const origin = getConfig().printConsoleTrace && !disableStack ? new Error('STACK_TRACE').stack?.split('\n').slice(1).join('\n') @@ -136,5 +137,6 @@ function sendLog(type: 'stdout' | 'stderr', content: string, disableStack?: bool taskId, type, size: content.length, + ...(task && getCurrentAttempt(task)), }) } diff --git a/packages/vitest/src/public/browser.ts b/packages/vitest/src/public/browser.ts index 53be6ccbba9d..88c40bb8fdd1 100644 --- a/packages/vitest/src/public/browser.ts +++ b/packages/vitest/src/public/browser.ts @@ -6,6 +6,7 @@ export { takeCoverageInsideWorker, } from '../integrations/coverage' export { collectTests, startTests } from '../runtime/runner/run' +export { getCurrentAttempt } from '../runtime/runner/test-state' export type { FileSpecification } from '../runtime/runner/types' export { loadDiffConfig, diff --git a/packages/vitest/src/runtime/console.ts b/packages/vitest/src/runtime/console.ts index 9e61a9c28a99..f40257920f94 100644 --- a/packages/vitest/src/runtime/console.ts +++ b/packages/vitest/src/runtime/console.ts @@ -1,9 +1,11 @@ import type { WorkerGlobalState } from '../types/worker' +import type { TestAttemptIndex } from './runner/test-state' import { Console } from 'node:console' import { relative } from 'node:path' import { Writable } from 'node:stream' import { getSafeTimers } from '@vitest/utils/timers' import c from 'tinyrainbow' +import { getCurrentAttempt } from './runner/test-state' import { EnvironmentTeardownError, getWorkerState } from './utils' const RealDate = globalThis.Date @@ -36,7 +38,16 @@ function getTaskIdByStack(root: string) { export function createCustomConsole(defaultState?: WorkerGlobalState): Console { const stdoutBuffer = new Map() const stderrBuffer = new Map() - const timers = new Map void }>() + const timers = new Map< + string, + { + taskId: string + attempt?: TestAttemptIndex + stdoutTime: number + stderrTime: number + cancel?: () => void + } + >() const { queueMicrotask } = getSafeTimers() @@ -54,45 +65,53 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { const state = () => defaultState || getWorkerState() + function getLogTarget() { + const s = state() + const taskId = s.current?.id || getTaskIdByStack(s.config.root) + const attempt = s.current && getCurrentAttempt(s.current) + const key = attempt ? `${taskId}:${attempt.repeatIndex}:${attempt.retryIndex}` : taskId + return { key, taskId, attempt } + } + // group sync console.log calls with micro task - function schedule(taskId: string) { - const timer = timers.get(taskId)! + function schedule(key: string) { + const timer = timers.get(key)! const { stdoutTime, stderrTime } = timer timer.cancel?.() timer.cancel = queueCancelableMicrotask(() => { if (stderrTime < stdoutTime) { - sendStderr(taskId) - sendStdout(taskId) + sendStderr(key) + sendStdout(key) } else { - sendStdout(taskId) - sendStderr(taskId) + sendStdout(key) + sendStderr(key) } }) } - function sendStdout(taskId: string) { - sendBuffer('stdout', taskId) + function sendStdout(key: string) { + sendBuffer('stdout', key) } - function sendStderr(taskId: string) { - sendBuffer('stderr', taskId) + function sendStderr(key: string) { + sendBuffer('stderr', key) } - function sendBuffer(type: 'stdout' | 'stderr', taskId: string) { + function sendBuffer(type: 'stdout' | 'stderr', key: string) { const buffers = type === 'stdout' ? stdoutBuffer : stderrBuffer - const buffer = buffers.get(taskId) + const buffer = buffers.get(key) if (!buffer) { return } if (state().config.printConsoleTrace) { buffer.forEach(([buffer, origin]) => { - sendLog(type, taskId, String(buffer), buffer.length, origin) + sendLog(type, key, String(buffer), buffer.length, origin) }) } else { const content = buffer.map((i) => String(i[0])).join('') - sendLog(type, taskId, content, buffer.length) + sendLog(type, key, content, buffer.length) } - const timer = timers.get(taskId)! - buffers.delete(taskId) + const timer = timers.get(key)! + buffers.delete(key) if (type === 'stderr') { timer.stderrTime = 0 } else { @@ -102,21 +121,22 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { function sendLog( type: 'stderr' | 'stdout', - taskId: string, + key: string, content: string, size: number, origin?: string, ) { - const timer = timers.get(taskId)! + const timer = timers.get(key)! const time = type === 'stderr' ? timer.stderrTime : timer.stdoutTime state() .rpc.onUserConsoleLog({ type, content: content || '', - taskId, + taskId: timer.taskId, time: time || RealDate.now(), size, origin, + ...timer.attempt, }) .catch((error) => { // the log is already sent, the worker only closed before the reporter answered @@ -128,22 +148,23 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { const stdout = new Writable({ write(data, encoding, callback) { - const s = state() - const id = s.current?.id || getTaskIdByStack(s.config.root) - let timer = timers.get(id) + const { key, taskId, attempt } = getLogTarget() + let timer = timers.get(key) if (timer) { timer.stdoutTime = timer.stdoutTime || RealDate.now() } else { timer = { + taskId, + attempt, stdoutTime: RealDate.now(), stderrTime: 0, } - timers.set(id, timer) + timers.set(key, timer) } - let buffer = stdoutBuffer.get(id) + let buffer = stdoutBuffer.get(key) if (!buffer) { buffer = [] - stdoutBuffer.set(id, buffer) + stdoutBuffer.set(key, buffer) } if (state().config.printConsoleTrace) { const limit = Error.stackTraceLimit @@ -155,28 +176,29 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { } else { buffer.push([data, undefined]) } - schedule(id) + schedule(key) callback() }, }) const stderr = new Writable({ write(data, encoding, callback) { - const s = state() - const id = s.current?.id || getTaskIdByStack(s.config.root) - let timer = timers.get(id) + const { key, taskId, attempt } = getLogTarget() + let timer = timers.get(key) if (timer) { timer.stderrTime = timer.stderrTime || RealDate.now() } else { timer = { + taskId, + attempt, stderrTime: RealDate.now(), stdoutTime: 0, } - timers.set(id, timer) + timers.set(key, timer) } - let buffer = stderrBuffer.get(id) + let buffer = stderrBuffer.get(key) if (!buffer) { buffer = [] - stderrBuffer.set(id, buffer) + stderrBuffer.set(key, buffer) } if (state().config.printConsoleTrace) { const limit = Error.stackTraceLimit @@ -194,7 +216,7 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { } else { buffer.push([data, undefined]) } - schedule(id) + schedule(key) callback() }, }) diff --git a/packages/vitest/src/runtime/runner/run.ts b/packages/vitest/src/runtime/runner/run.ts index 34283751f039..5d93d992de3e 100644 --- a/packages/vitest/src/runtime/runner/run.ts +++ b/packages/vitest/src/runtime/runner/run.ts @@ -48,7 +48,7 @@ import { getBeforeHookCleanupCallback, } from './hooks' import { getFn, getHooks } from './map' -import { addRunningTest, getRunningTests, setCurrentTest } from './test-state' +import { addRunningTest, getRunningTests, setCurrentAttempt, setCurrentTest } from './test-state' import { partitionSuiteChildren } from './utils/suite' const now = globalThis.performance @@ -624,6 +624,7 @@ async function runTest(test: Test, runner: VitestRunner): Promise { if (retryCount > 0 || repeatCount > 0) { resetContextSignal(test.context) } + setCurrentAttempt(test, { retryIndex: retryCount, repeatIndex: repeatCount }) const attemptStart = now() const attemptStartTime = unixNow() const attemptErrorsStart = test.result.errors?.length ?? 0 diff --git a/packages/vitest/src/runtime/runner/test-state.ts b/packages/vitest/src/runtime/runner/test-state.ts index 6fd41996d885..43c855e29a49 100644 --- a/packages/vitest/src/runtime/runner/test-state.ts +++ b/packages/vitest/src/runtime/runner/test-state.ts @@ -1,4 +1,4 @@ -import type { Test } from './types' +import type { Task, Test } from './types' let _test: Test | undefined @@ -21,3 +21,18 @@ export function addRunningTest(test: Test): () => void { export function getRunningTests(): ReadonlySet { return tests } + +export interface TestAttemptIndex { + retryIndex: number + repeatIndex: number +} + +const currentAttempts = new WeakMap() + +export function setCurrentAttempt(test: Test, attempt: TestAttemptIndex): void { + currentAttempts.set(test, attempt) +} + +export function getCurrentAttempt(task: Task): TestAttemptIndex | undefined { + return currentAttempts.get(task) +} diff --git a/packages/vitest/src/types/general.ts b/packages/vitest/src/types/general.ts index 4a670412bc5c..eb3a9204c350 100644 --- a/packages/vitest/src/types/general.ts +++ b/packages/vitest/src/types/general.ts @@ -19,6 +19,10 @@ export interface UserConsoleLog { taskId?: string time: number size: number + /** The zero-based retry index of the attempt that printed the log. */ + retryIndex?: number + /** The zero-based repeat index of the attempt that printed the log. */ + repeatIndex?: number } interface ModuleGraphModules { diff --git a/test/browser/specs/runner.test.ts b/test/browser/specs/runner.test.ts index 5246ff9468e4..0bf7e53019e0 100644 --- a/test/browser/specs/runner.test.ts +++ b/test/browser/specs/runner.test.ts @@ -4,7 +4,7 @@ import { readdirSync } from 'node:fs' import { readFile } from 'node:fs/promises' import { beforeAll, describe, expect, onTestFailed, test } from 'vitest' import { buildTestTree } from '../../test-utils' -import { instances, provider, runBrowserTests } from './utils' +import { instances, provider, runBrowserTests, runInlineBrowserTests } from './utils' function noop() {} @@ -282,6 +282,55 @@ test('disableConsoleIntercept', async () => { expect(result.stdout).not.toContain('hello from console.log') }) +test('console logs have the attempt that printed them', async () => { + const logs: string[] = [] + const { stderr, testTree } = await runInlineBrowserTests( + { + 'basic.test.ts': ` + import { beforeAll, expect, test } from 'vitest' + + beforeAll(() => { + console.log('beforeAll') + }) + + let runs = 0 + test('repeats', { repeats: 1, retry: 1 }, () => { + console.log('test') + expect(++runs % 2).toBe(0) + }) + `, + }, + { + browser: { instances: [instances[0]] }, + reporters: [ + { + onUserConsoleLog(log) { + logs.push(`${log.repeatIndex}/${log.retryIndex} ${log.content.trim()}`) + }, + }, + ], + }, + ) + + expect(stderr).toBe('') + expect(testTree()).toMatchInlineSnapshot(` + { + "basic.test.ts": { + "repeats": "passed", + }, + } + `) + expect(logs).toMatchInlineSnapshot(` + [ + "undefined/undefined beforeAll", + "0/0 test", + "0/1 test", + "1/0 test", + "1/1 test", + ] + `) +}) + test(`stack trace points to correct file in every browser when failed`, async () => { expect.assertions(30) const { stderr } = await runBrowserTests({ diff --git a/test/e2e/test/console.test.ts b/test/e2e/test/console.test.ts index 8bfa7e550fde..348fae557221 100644 --- a/test/e2e/test/console.test.ts +++ b/test/e2e/test/console.test.ts @@ -194,3 +194,106 @@ test('console log sent while the worker closes is not reported as an error', asy } `) }) + +test('console logs have the attempt that printed them', async () => { + const logs: string[] = [] + const { stderr, testTree } = await runInlineTests( + { + 'basic.test.ts': ts` + import { aroundEach, beforeAll, beforeEach, afterEach, expect, test as base } from 'vitest' + + const test = base.extend('fixture', async ({}, { onCleanup }) => { + onCleanup(() => console.log('fixture teardown')) + }) + + beforeAll(() => { + console.log('beforeAll') + }) + + aroundEach(async (runTest) => { + console.log('aroundEach') + await runTest() + }) + + beforeEach(() => { + console.log('beforeEach') + }) + + afterEach(() => { + console.error('afterEach') + }) + + let retries = 0 + test('retry', { retry: 2 }, ({ fixture }) => { + console.log('test') + expect(++retries).toBe(3) + }) + + let repeats = 0 + test('repeats', { repeats: 1, retry: 1 }, ({ fixture }) => { + console.log('test') + expect(++repeats % 2).toBe(0) + }) + `, + }, + { + reporters: [ + { + onUserConsoleLog(log) { + logs.push(`${log.repeatIndex}/${log.retryIndex} ${log.type} ${log.content.trim()}`) + }, + }, + ], + }, + ) + + expect(stderr).toBe('') + expect(testTree()).toMatchInlineSnapshot(` + { + "basic.test.ts": { + "repeats": "passed", + "retry": "passed", + }, + } + `) + expect(logs).toMatchInlineSnapshot(` + [ + "undefined/undefined stdout beforeAll", + "0/0 stdout aroundEach", + "0/0 stdout beforeEach", + "0/0 stdout test", + "0/0 stderr afterEach", + "0/0 stdout fixture teardown", + "0/1 stdout aroundEach", + "0/1 stdout beforeEach", + "0/1 stdout test", + "0/1 stderr afterEach", + "0/1 stdout fixture teardown", + "0/2 stdout aroundEach", + "0/2 stdout beforeEach", + "0/2 stdout test", + "0/2 stderr afterEach", + "0/2 stdout fixture teardown", + "0/0 stdout aroundEach", + "0/0 stdout beforeEach", + "0/0 stdout test", + "0/0 stderr afterEach", + "0/0 stdout fixture teardown", + "0/1 stdout aroundEach", + "0/1 stdout beforeEach", + "0/1 stdout test", + "0/1 stderr afterEach", + "0/1 stdout fixture teardown", + "1/0 stdout aroundEach", + "1/0 stdout beforeEach", + "1/0 stdout test", + "1/0 stderr afterEach", + "1/0 stdout fixture teardown", + "1/1 stdout aroundEach", + "1/1 stdout beforeEach", + "1/1 stdout test", + "1/1 stderr afterEach", + "1/1 stdout fixture teardown", + ] + `) +}) From 89d39ea37fff6f05ffcbba5b08f6a5eecbfbbbe1 Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa <4232207+hi-ogawa@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:44:19 +0900 Subject: [PATCH 2/9] fix: attribute console logs to attempts in vm pools Co-Authored-By: Claude Opus 5.5 --- packages/browser/src/client/tester/logger.ts | 7 ++-- packages/vitest/src/public/browser.ts | 2 +- packages/vitest/src/runtime/console.ts | 3 +- packages/vitest/src/runtime/runners/test.ts | 3 ++ packages/vitest/src/types/worker.ts | 6 ++- test/e2e/test/console.test.ts | 42 +++++++++++--------- 6 files changed, 37 insertions(+), 26 deletions(-) diff --git a/packages/browser/src/client/tester/logger.ts b/packages/browser/src/client/tester/logger.ts index 2b1dbcd68a5d..e7817fb5ddb8 100644 --- a/packages/browser/src/client/tester/logger.ts +++ b/packages/browser/src/client/tester/logger.ts @@ -1,4 +1,4 @@ -import { format, getCurrentAttempt } from 'vitest/internal/browser' +import { format } from 'vitest/internal/browser' import { getConfig } from '../utils' import { rpc } from './rpc' import { getBrowserRunner } from './runner' @@ -122,7 +122,8 @@ function sendLog(type: 'stdout' | 'stderr', content: string, disableStack?: bool } const unknownTestId = '__vitest__unknown_test__' // @ts-expect-error untyped global - const task = globalThis.__vitest_worker__?.current + const state = globalThis.__vitest_worker__ + const task = state?.current const taskId = task?.id ?? unknownTestId const origin = getConfig().printConsoleTrace && !disableStack @@ -137,6 +138,6 @@ function sendLog(type: 'stdout' | 'stderr', content: string, disableStack?: bool taskId, type, size: content.length, - ...(task?.type === 'test' && getCurrentAttempt(task)), + ...(task?.type === 'test' && state.getCurrentAttempt?.(task)), }) } diff --git a/packages/vitest/src/public/browser.ts b/packages/vitest/src/public/browser.ts index 72304081300c..53be6ccbba9d 100644 --- a/packages/vitest/src/public/browser.ts +++ b/packages/vitest/src/public/browser.ts @@ -5,7 +5,7 @@ export { stopCoverageInsideWorker, takeCoverageInsideWorker, } from '../integrations/coverage' -export { collectTests, getCurrentAttempt, startTests } from '../runtime/runner/run' +export { collectTests, startTests } from '../runtime/runner/run' export type { FileSpecification } from '../runtime/runner/types' export { loadDiffConfig, diff --git a/packages/vitest/src/runtime/console.ts b/packages/vitest/src/runtime/console.ts index 15c050f9086c..ab791ab66959 100644 --- a/packages/vitest/src/runtime/console.ts +++ b/packages/vitest/src/runtime/console.ts @@ -4,7 +4,6 @@ import { relative } from 'node:path' import { Writable } from 'node:stream' import { getSafeTimers } from '@vitest/utils/timers' import c from 'tinyrainbow' -import { getCurrentAttempt } from './runner/run' import { getCurrentTask } from './runner/test-state' import { EnvironmentTeardownError, getWorkerState } from './utils' @@ -69,7 +68,7 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console { const s = state() const task = getCurrentTask() ?? s.current const taskId = task?.id || getTaskIdByStack(s.config.root) - const attempt = task?.type === 'test' ? getCurrentAttempt(task) : undefined + const attempt = task?.type === 'test' ? s.getCurrentAttempt?.(task) : undefined const key = attempt ? `${taskId}:${attempt.repeatIndex}:${attempt.retryIndex}` : taskId return { key, taskId, attempt } } diff --git a/packages/vitest/src/runtime/runners/test.ts b/packages/vitest/src/runtime/runners/test.ts index 5f8e5fa7d3bf..02adbbd67e7f 100644 --- a/packages/vitest/src/runtime/runners/test.ts +++ b/packages/vitest/src/runtime/runners/test.ts @@ -28,6 +28,7 @@ import { createBench, kFinalize } from '../benchmark' import { rpc } from '../rpc' import { getTestFakes, hasOwnRandomFakes, setTestFakesRestore } from '../runner/fakes' import { getFn, getHooks } from '../runner/map' +import { getCurrentAttempt } from '../runner/run' import { createTaskCollector, getCurrentSuite } from '../runner/suite' import { getCurrentTest } from '../runner/test-state' import { createChainable } from '../runner/utils/chain' @@ -59,6 +60,8 @@ export class TestRunner implements VitestTestRunner { const environment = this.workerState.environment this.viteEnvironment = environment.viteEnvironment || environment.name this.viteModuleRunner = config.experimental.viteModuleRunner + // the console of vm pools runs in another copy of the runner modules + this.workerState.getCurrentAttempt = getCurrentAttempt // vm pools downgrade worker-scoped fixtures to file scope, so the hook has // nothing to tear down there; registering it anyway would keep the // listener, an in-context closure, alive for the lifetime of the worker diff --git a/packages/vitest/src/types/worker.ts b/packages/vitest/src/types/worker.ts index 43e4f2fe4ef1..6806d49c8252 100644 --- a/packages/vitest/src/types/worker.ts +++ b/packages/vitest/src/types/worker.ts @@ -3,7 +3,7 @@ import type { EvaluatedModules } from 'vite/module-runner' import type { SerializedConfig } from '../runtime/config' import type { GetterTracker } from '../runtime/getter-tracker' import type { CurrentContextStore } from '../runtime/runner/test-state' -import type { CancelReason, FileSpecification, Task } from '../runtime/runner/types' +import type { CancelReason, FileSpecification, Task, Test } from '../runtime/runner/types' import type { Traces } from '../utils/traces' import type { Environment } from './environment' import type { RunnerRPC, RuntimeRPC } from './rpc' @@ -83,6 +83,10 @@ export interface WorkerGlobalState { resolvingModules: Set moduleExecutionInfo: Map currentContext?: CurrentContextStore + /** + * @internal + */ + getCurrentAttempt?: (test: Test) => { retryIndex: number; repeatIndex: number } | undefined /** * Module ids and file paths loaded by the current test file. Only set when * `experimental.recordDependencies` is enabled. diff --git a/test/e2e/test/console.test.ts b/test/e2e/test/console.test.ts index 348fae557221..a236c9298c16 100644 --- a/test/e2e/test/console.test.ts +++ b/test/e2e/test/console.test.ts @@ -195,11 +195,13 @@ test('console log sent while the worker closes is not reported as an error', asy `) }) -test('console logs have the attempt that printed them', async () => { - const logs: string[] = [] - const { stderr, testTree } = await runInlineTests( - { - 'basic.test.ts': ts` +test.for(['threads', 'vmThreads'])( + 'console logs have the attempt that printed them in %s', + async (pool) => { + const logs: string[] = [] + const { stderr, testTree } = await runInlineTests( + { + 'basic.test.ts': ts` import { aroundEach, beforeAll, beforeEach, afterEach, expect, test as base } from 'vitest' const test = base.extend('fixture', async ({}, { onCleanup }) => { @@ -235,20 +237,21 @@ test('console logs have the attempt that printed them', async () => { expect(++repeats % 2).toBe(0) }) `, - }, - { - reporters: [ - { - onUserConsoleLog(log) { - logs.push(`${log.repeatIndex}/${log.retryIndex} ${log.type} ${log.content.trim()}`) + }, + { + pool, + reporters: [ + { + onUserConsoleLog(log) { + logs.push(`${log.repeatIndex}/${log.retryIndex} ${log.type} ${log.content.trim()}`) + }, }, - }, - ], - }, - ) + ], + }, + ) - expect(stderr).toBe('') - expect(testTree()).toMatchInlineSnapshot(` + expect(stderr).toBe('') + expect(testTree()).toMatchInlineSnapshot(` { "basic.test.ts": { "repeats": "passed", @@ -256,7 +259,7 @@ test('console logs have the attempt that printed them', async () => { }, } `) - expect(logs).toMatchInlineSnapshot(` + expect(logs).toMatchInlineSnapshot(` [ "undefined/undefined stdout beforeAll", "0/0 stdout aroundEach", @@ -296,4 +299,5 @@ test('console logs have the attempt that printed them', async () => { "1/1 stdout fixture teardown", ] `) -}) + }, +) From c167cc66976b1c89c05bfcabfd169747f20fae38 Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa <4232207+hi-ogawa@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:11:58 +0900 Subject: [PATCH 3/9] test: reduce console attempt test to what the console owns Co-Authored-By: Claude Opus 5.5 --- test/e2e/test/console.test.ts | 100 +++++++++------------------------- 1 file changed, 25 insertions(+), 75 deletions(-) diff --git a/test/e2e/test/console.test.ts b/test/e2e/test/console.test.ts index a236c9298c16..771e4ec3d127 100644 --- a/test/e2e/test/console.test.ts +++ b/test/e2e/test/console.test.ts @@ -202,39 +202,17 @@ test.for(['threads', 'vmThreads'])( const { stderr, testTree } = await runInlineTests( { 'basic.test.ts': ts` - import { aroundEach, beforeAll, beforeEach, afterEach, expect, test as base } from 'vitest' - - const test = base.extend('fixture', async ({}, { onCleanup }) => { - onCleanup(() => console.log('fixture teardown')) - }) + import { beforeAll, expect, test } from 'vitest' beforeAll(() => { console.log('beforeAll') }) - aroundEach(async (runTest) => { - console.log('aroundEach') - await runTest() - }) - - beforeEach(() => { - console.log('beforeEach') - }) - - afterEach(() => { - console.error('afterEach') - }) - - let retries = 0 - test('retry', { retry: 2 }, ({ fixture }) => { - console.log('test') - expect(++retries).toBe(3) - }) - - let repeats = 0 - test('repeats', { repeats: 1, retry: 1 }, ({ fixture }) => { - console.log('test') - expect(++repeats % 2).toBe(0) + let runs = 0 + test('repeats', { repeats: 1, retry: 1 }, () => { + console.log('stdout') + console.error('stderr') + expect(++runs % 2).toBe(0) }) `, }, @@ -243,7 +221,7 @@ test.for(['threads', 'vmThreads'])( reporters: [ { onUserConsoleLog(log) { - logs.push(`${log.repeatIndex}/${log.retryIndex} ${log.type} ${log.content.trim()}`) + logs.push(`${log.repeatIndex}/${log.retryIndex} ${log.content.trim()}`) }, }, ], @@ -252,52 +230,24 @@ test.for(['threads', 'vmThreads'])( expect(stderr).toBe('') expect(testTree()).toMatchInlineSnapshot(` - { - "basic.test.ts": { - "repeats": "passed", - "retry": "passed", - }, - } - `) + { + "basic.test.ts": { + "repeats": "passed", + }, + } + `) expect(logs).toMatchInlineSnapshot(` - [ - "undefined/undefined stdout beforeAll", - "0/0 stdout aroundEach", - "0/0 stdout beforeEach", - "0/0 stdout test", - "0/0 stderr afterEach", - "0/0 stdout fixture teardown", - "0/1 stdout aroundEach", - "0/1 stdout beforeEach", - "0/1 stdout test", - "0/1 stderr afterEach", - "0/1 stdout fixture teardown", - "0/2 stdout aroundEach", - "0/2 stdout beforeEach", - "0/2 stdout test", - "0/2 stderr afterEach", - "0/2 stdout fixture teardown", - "0/0 stdout aroundEach", - "0/0 stdout beforeEach", - "0/0 stdout test", - "0/0 stderr afterEach", - "0/0 stdout fixture teardown", - "0/1 stdout aroundEach", - "0/1 stdout beforeEach", - "0/1 stdout test", - "0/1 stderr afterEach", - "0/1 stdout fixture teardown", - "1/0 stdout aroundEach", - "1/0 stdout beforeEach", - "1/0 stdout test", - "1/0 stderr afterEach", - "1/0 stdout fixture teardown", - "1/1 stdout aroundEach", - "1/1 stdout beforeEach", - "1/1 stdout test", - "1/1 stderr afterEach", - "1/1 stdout fixture teardown", - ] - `) + [ + "undefined/undefined beforeAll", + "0/0 stdout", + "0/0 stderr", + "0/1 stdout", + "0/1 stderr", + "1/0 stdout", + "1/0 stderr", + "1/1 stdout", + "1/1 stderr", + ] + `) }, ) From 195811555da1a44604787f94e36c15b2581d0864 Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa <4232207+hi-ogawa@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:15:54 +0900 Subject: [PATCH 4/9] docs: write out `UserConsoleLog` Co-Authored-By: Claude Opus 5.5 --- docs/api/advanced/test-case.md | 37 +++++++++++++++++++++++++++- docs/api/advanced/test-module.md | 2 +- docs/api/advanced/test-suite.md | 2 +- packages/vitest/src/types/general.ts | 5 ++++ 4 files changed, 43 insertions(+), 3 deletions(-) diff --git a/docs/api/advanced/test-case.md b/docs/api/advanced/test-case.md index efd76cf633e8..2ae473101815 100644 --- a/docs/api/advanced/test-case.md +++ b/docs/api/advanced/test-case.md @@ -390,4 +390,39 @@ function logs(): ReadonlyArray Console logs recorded during the test execution. -Each log printed during an attempt has the `retryIndex` and `repeatIndex` of that attempt, so it can be matched with an entry of [`attempts()`](#attempts). +```ts +interface UserConsoleLog { + /** + * The printed text. + */ + content: string + /** + * The stack trace of the console call, when `printConsoleTrace` is enabled. + */ + origin?: string + /** + * Whether the log was printed in browser mode. + */ + browser?: boolean + type: 'stdout' | 'stderr' + /** + * The id of the task that printed the log. + */ + taskId?: string + /** + * Time in milliseconds when the log was printed. + */ + time: number + size: number + /** + * The zero-based retry index of the attempt that printed the log. + */ + retryIndex?: number + /** + * The zero-based repeat index of the attempt that printed the log. + */ + repeatIndex?: number +} +``` + +`retryIndex` and `repeatIndex` match an entry of [`attempts()`](#attempts). Logs printed outside a test attempt have neither. diff --git a/docs/api/advanced/test-module.md b/docs/api/advanced/test-module.md index a8339b10280e..dfe03c2a6ec1 100644 --- a/docs/api/advanced/test-module.md +++ b/docs/api/advanced/test-module.md @@ -155,7 +155,7 @@ interface ImportDuration { function logs(): ReadonlyArray ``` -Console logs recorded on top level of the module during test collection. For example: +Console logs ([`UserConsoleLog`](/api/advanced/test-case#logs)) recorded on top level of the module during test collection. For example: ```ts console.log('included') // [!code highlight] diff --git a/docs/api/advanced/test-suite.md b/docs/api/advanced/test-suite.md index c3add3bcfa78..507688c262bc 100644 --- a/docs/api/advanced/test-suite.md +++ b/docs/api/advanced/test-suite.md @@ -229,7 +229,7 @@ If metadata was attached during collection (outside of the `test` function), the function logs(): ReadonlyArray ``` -Console logs recorded during test collection of this suite. For example: +Console logs ([`UserConsoleLog`](/api/advanced/test-case#logs)) recorded during test collection of this suite. For example: ```ts describe('suite', () => { diff --git a/packages/vitest/src/types/general.ts b/packages/vitest/src/types/general.ts index 459c19925644..d363258ba0eb 100644 --- a/packages/vitest/src/types/general.ts +++ b/packages/vitest/src/types/general.ts @@ -13,11 +13,16 @@ export interface AfterSuiteRunMeta { } export interface UserConsoleLog { + /** The printed text. */ content: string + /** The stack trace of the console call, when `printConsoleTrace` is enabled. */ origin?: string + /** Whether the log was printed in browser mode. */ browser?: boolean type: 'stdout' | 'stderr' + /** The id of the task that printed the log. */ taskId?: string + /** Time in milliseconds when the log was printed. */ time: number size: number /** The zero-based retry index of the attempt that printed the log. */ From e52ac30b133e13d84fc4695c42d96494eede74db Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa <4232207+hi-ogawa@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:17:54 +0900 Subject: [PATCH 5/9] Revert "docs: write out `UserConsoleLog`" Moved to a separate docs PR. Co-Authored-By: Claude Opus 5.5 --- docs/api/advanced/test-case.md | 37 +--------------------------- docs/api/advanced/test-module.md | 2 +- docs/api/advanced/test-suite.md | 2 +- packages/vitest/src/types/general.ts | 5 ---- 4 files changed, 3 insertions(+), 43 deletions(-) diff --git a/docs/api/advanced/test-case.md b/docs/api/advanced/test-case.md index 2ae473101815..efd76cf633e8 100644 --- a/docs/api/advanced/test-case.md +++ b/docs/api/advanced/test-case.md @@ -390,39 +390,4 @@ function logs(): ReadonlyArray Console logs recorded during the test execution. -```ts -interface UserConsoleLog { - /** - * The printed text. - */ - content: string - /** - * The stack trace of the console call, when `printConsoleTrace` is enabled. - */ - origin?: string - /** - * Whether the log was printed in browser mode. - */ - browser?: boolean - type: 'stdout' | 'stderr' - /** - * The id of the task that printed the log. - */ - taskId?: string - /** - * Time in milliseconds when the log was printed. - */ - time: number - size: number - /** - * The zero-based retry index of the attempt that printed the log. - */ - retryIndex?: number - /** - * The zero-based repeat index of the attempt that printed the log. - */ - repeatIndex?: number -} -``` - -`retryIndex` and `repeatIndex` match an entry of [`attempts()`](#attempts). Logs printed outside a test attempt have neither. +Each log printed during an attempt has the `retryIndex` and `repeatIndex` of that attempt, so it can be matched with an entry of [`attempts()`](#attempts). diff --git a/docs/api/advanced/test-module.md b/docs/api/advanced/test-module.md index dfe03c2a6ec1..a8339b10280e 100644 --- a/docs/api/advanced/test-module.md +++ b/docs/api/advanced/test-module.md @@ -155,7 +155,7 @@ interface ImportDuration { function logs(): ReadonlyArray ``` -Console logs ([`UserConsoleLog`](/api/advanced/test-case#logs)) recorded on top level of the module during test collection. For example: +Console logs recorded on top level of the module during test collection. For example: ```ts console.log('included') // [!code highlight] diff --git a/docs/api/advanced/test-suite.md b/docs/api/advanced/test-suite.md index 507688c262bc..c3add3bcfa78 100644 --- a/docs/api/advanced/test-suite.md +++ b/docs/api/advanced/test-suite.md @@ -229,7 +229,7 @@ If metadata was attached during collection (outside of the `test` function), the function logs(): ReadonlyArray ``` -Console logs ([`UserConsoleLog`](/api/advanced/test-case#logs)) recorded during test collection of this suite. For example: +Console logs recorded during test collection of this suite. For example: ```ts describe('suite', () => { diff --git a/packages/vitest/src/types/general.ts b/packages/vitest/src/types/general.ts index d363258ba0eb..459c19925644 100644 --- a/packages/vitest/src/types/general.ts +++ b/packages/vitest/src/types/general.ts @@ -13,16 +13,11 @@ export interface AfterSuiteRunMeta { } export interface UserConsoleLog { - /** The printed text. */ content: string - /** The stack trace of the console call, when `printConsoleTrace` is enabled. */ origin?: string - /** Whether the log was printed in browser mode. */ browser?: boolean type: 'stdout' | 'stderr' - /** The id of the task that printed the log. */ taskId?: string - /** Time in milliseconds when the log was printed. */ time: number size: number /** The zero-based retry index of the attempt that printed the log. */ From 8c43974a43331fbe9c9026b626b7df9ba0962ecc Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa <4232207+hi-ogawa@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:20:01 +0900 Subject: [PATCH 6/9] refactor: move attempt lookup note to its type Co-Authored-By: Claude Opus 5.5 --- packages/vitest/src/runtime/runners/test.ts | 1 - packages/vitest/src/types/worker.ts | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vitest/src/runtime/runners/test.ts b/packages/vitest/src/runtime/runners/test.ts index 02adbbd67e7f..4bd6c4e4e937 100644 --- a/packages/vitest/src/runtime/runners/test.ts +++ b/packages/vitest/src/runtime/runners/test.ts @@ -60,7 +60,6 @@ export class TestRunner implements VitestTestRunner { const environment = this.workerState.environment this.viteEnvironment = environment.viteEnvironment || environment.name this.viteModuleRunner = config.experimental.viteModuleRunner - // the console of vm pools runs in another copy of the runner modules this.workerState.getCurrentAttempt = getCurrentAttempt // vm pools downgrade worker-scoped fixtures to file scope, so the hook has // nothing to tear down there; registering it anyway would keep the diff --git a/packages/vitest/src/types/worker.ts b/packages/vitest/src/types/worker.ts index 6806d49c8252..5243fe0825c4 100644 --- a/packages/vitest/src/types/worker.ts +++ b/packages/vitest/src/types/worker.ts @@ -85,6 +85,7 @@ export interface WorkerGlobalState { currentContext?: CurrentContextStore /** * @internal + * vm pools load the runner modules twice, so the console reads the attempt through the worker state */ getCurrentAttempt?: (test: Test) => { retryIndex: number; repeatIndex: number } | undefined /** From a4385f2f0d0aae0d246d35776381e81a33bfc0ac Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa <4232207+hi-ogawa@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:20:53 +0900 Subject: [PATCH 7/9] refactor: clarify attempt lookup note Co-Authored-By: Claude Opus 5.5 --- packages/vitest/src/types/worker.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/vitest/src/types/worker.ts b/packages/vitest/src/types/worker.ts index 5243fe0825c4..983ffce15b92 100644 --- a/packages/vitest/src/types/worker.ts +++ b/packages/vitest/src/types/worker.ts @@ -85,7 +85,8 @@ export interface WorkerGlobalState { currentContext?: CurrentContextStore /** * @internal - * vm pools load the runner modules twice, so the console reads the attempt through the worker state + * vm pools load the runner modules twice, so the console reads the attempt through the worker state, + * which both copies share, to see the same attempts as the runner */ getCurrentAttempt?: (test: Test) => { retryIndex: number; repeatIndex: number } | undefined /** From 04b06e34e4a615d41c3c38c8868d0f22ab00122d Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa <4232207+hi-ogawa@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:09:33 +0900 Subject: [PATCH 8/9] docs: drop repeated note on attempt indexes Co-Authored-By: Claude Opus 5.5 --- docs/api/advanced/test-case.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/api/advanced/test-case.md b/docs/api/advanced/test-case.md index c64933978772..e825d16148a3 100644 --- a/docs/api/advanced/test-case.md +++ b/docs/api/advanced/test-case.md @@ -424,5 +424,3 @@ interface UserConsoleLog { repeatIndex?: number } ``` - -Each log printed during an attempt has the `retryIndex` and `repeatIndex` of that attempt, so it can be matched with an entry of [`attempts()`](#attempts). From 6688bf84f8b684304ee7a4e93cc9d81d2eec424c Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa <4232207+hi-ogawa@users.noreply.github.com> Date: Tue, 1 Dec 2026 18:23:37 +0900 Subject: [PATCH 9/9] chore: fix jsdoc lint warning Co-Authored-By: Claude Opus 5.5 --- packages/vitest/src/types/worker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/vitest/src/types/worker.ts b/packages/vitest/src/types/worker.ts index 983ffce15b92..07cd443f01b6 100644 --- a/packages/vitest/src/types/worker.ts +++ b/packages/vitest/src/types/worker.ts @@ -84,9 +84,9 @@ export interface WorkerGlobalState { moduleExecutionInfo: Map currentContext?: CurrentContextStore /** - * @internal * vm pools load the runner modules twice, so the console reads the attempt through the worker state, * which both copies share, to see the same attempts as the runner + * @internal */ getCurrentAttempt?: (test: Test) => { retryIndex: number; repeatIndex: number } | undefined /**