11import { Writable } from 'node:stream'
22import { Console } from 'node:console'
3+ import { relative } from 'node:path'
34import { getSafeTimers } from '@vitest/utils'
45import { RealDate } from '../integrations/mock/date'
56import type { WorkerGlobalState } from '../types'
67
8+ export const UNKNOWN_TEST_ID = '__vitest__unknown_test__'
9+
10+ function getTaskIdByStack ( root : string ) {
11+ const stack = new Error ( 'STACK_TRACE_ERROR' ) . stack ?. split ( '\n' )
12+
13+ if ( ! stack )
14+ return UNKNOWN_TEST_ID
15+
16+ const index = stack . findIndex ( line => line . includes ( 'at Console.value (node:internal/console/' ) )
17+ const line = index === - 1 ? null : stack [ index + 2 ]
18+
19+ if ( ! line )
20+ return UNKNOWN_TEST_ID
21+
22+ const filepath = line . match ( / a t \s ( .* ) \s ? / ) ?. [ 1 ]
23+
24+ if ( filepath )
25+ return relative ( root , filepath )
26+
27+ return UNKNOWN_TEST_ID
28+ }
29+
730export function createCustomConsole ( state : WorkerGlobalState ) {
831 const stdoutBuffer = new Map < string , any [ ] > ( )
932 const stderrBuffer = new Map < string , any [ ] > ( )
1033 const timers = new Map < string , { stdoutTime : number ; stderrTime : number ; timer : any } > ( )
11- const unknownTestId = '__vitest__unknown_test__'
1234
1335 const { setTimeout, clearTimeout } = getSafeTimers ( )
1436
@@ -63,7 +85,7 @@ export function createCustomConsole(state: WorkerGlobalState) {
6385
6486 const stdout = new Writable ( {
6587 write ( data , encoding , callback ) {
66- const id = state ?. current ?. id ?? unknownTestId
88+ const id = state ?. current ?. id ?? getTaskIdByStack ( state . ctx . config . root )
6789 let timer = timers . get ( id )
6890 if ( timer ) {
6991 timer . stdoutTime = timer . stdoutTime || RealDate . now ( )
@@ -84,7 +106,7 @@ export function createCustomConsole(state: WorkerGlobalState) {
84106 } )
85107 const stderr = new Writable ( {
86108 write ( data , encoding , callback ) {
87- const id = state ?. current ?. id ?? unknownTestId
109+ const id = state ?. current ?. id ?? getTaskIdByStack ( state . ctx . config . root )
88110 let timer = timers . get ( id )
89111 if ( timer ) {
90112 timer . stderrTime = timer . stderrTime || RealDate . now ( )
0 commit comments