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
25 changes: 16 additions & 9 deletions packages/vitest/src/runtime/console.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { relative } from 'node:path'
import { Writable } from 'node:stream'
import { getSafeTimers } from '@vitest/utils/timers'
import c from 'tinyrainbow'
import { getWorkerState } from './utils'
import { EnvironmentTeardownError, getWorkerState } from './utils'

const RealDate = globalThis.Date

Expand Down Expand Up @@ -109,14 +109,21 @@ export function createCustomConsole(defaultState?: WorkerGlobalState): Console {
) {
const timer = timers.get(taskId)!
const time = type === 'stderr' ? timer.stderrTime : timer.stdoutTime
state().rpc.onUserConsoleLog({
type,
content: content || '<empty line>',
taskId,
time: time || RealDate.now(),
size,
origin,
})
state()
.rpc.onUserConsoleLog({
type,
content: content || '<empty line>',
taskId,
time: time || RealDate.now(),
size,
origin,
})
.catch((error) => {
// the log is already sent, the worker only closed before the reporter answered
if (!(error instanceof EnvironmentTeardownError)) {
throw error
}
})
}

const stdout = new Writable({
Expand Down
44 changes: 43 additions & 1 deletion test/e2e/test/console.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { relative, resolve } from 'pathe'
import { expect, test } from 'vitest'
import { DefaultReporter } from 'vitest/node'
import { runInlineTests, runVitest } from '../../test-utils'
import { runInlineTests, runVitest, ts } from '../../test-utils'

test('can run custom pools with Vitest', async () => {
const reporter = new DefaultReporter()
Expand Down Expand Up @@ -152,3 +152,45 @@ test('onConsoleLog receives the entity', async () => {
]
`)
})

// https://github.com/vitest-dev/vitest/issues/11153
test('console log sent while the worker closes is not reported as an error', async () => {
const { stderr, testTree } = await runInlineTests(
{
'late-log.test.ts': ts`
import { test } from 'vitest'
test('logs and leaks an interval', () => {
console.log('log inside the test')
let ticks = 0
const interval = setInterval(() => {
console.log('log after the test')
if (++ticks === 50) {
clearInterval(interval)
}
}, 2)
})
`,
},
{
reporters: [
'verbose',
{
async onUserConsoleLog() {
// keep every log pending, so the worker closes while the late logs wait for an answer
await new Promise((resolve) => setTimeout(resolve, 20))
},
},
],
},
)

expect(stderr).toBe('')
expect(testTree()).toMatchInlineSnapshot(`
{
"late-log.test.ts": {
"logs and leaks an interval": "passed",
},
}
`)
})