Skip to content

Commit

Permalink
fix(vitest): print file path instead of "unknown test" when logging (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Dunqing committed Oct 5, 2023
1 parent 9350461 commit ec2e804
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 4 deletions.
3 changes: 2 additions & 1 deletion packages/vitest/src/node/reporters/base.ts
Expand Up @@ -4,6 +4,7 @@ import type { ErrorWithDiff, File, Reporter, Task, TaskResultPack, UserConsoleLo
import { getFullName, getSafeTimers, getSuites, getTests, hasFailed, hasFailedSnapshot, isCI, isNode, relativePath } from '../../utils'
import type { Vitest } from '../../node'
import { F_RIGHT } from '../../utils/figures'
import { UNKNOWN_TEST_ID } from '../../runtime/console'
import { countTestErrors, divider, formatProjectName, formatTimeString, getStateString, getStateSymbol, pointer, renderSnapshotSummary } from './renderers/utils'

const BADGE_PADDING = ' '
Expand Down Expand Up @@ -186,7 +187,7 @@ export abstract class BaseReporter implements Reporter {
if (!this.shouldLog(log))
return
const task = log.taskId ? this.ctx.state.idMap.get(log.taskId) : undefined
const header = c.gray(log.type + c.dim(` | ${task ? getFullName(task, c.dim(' > ')) : 'unknown test'}`))
const header = c.gray(log.type + c.dim(` | ${task ? getFullName(task, c.dim(' > ')) : log.taskId !== UNKNOWN_TEST_ID ? log.taskId : 'unknown test'}`))
process[log.type].write(`${header}\n${log.content}\n`)
}

Expand Down
28 changes: 25 additions & 3 deletions packages/vitest/src/runtime/console.ts
@@ -1,14 +1,36 @@
import { Writable } from 'node:stream'
import { Console } from 'node:console'
import { relative } from 'node:path'
import { getSafeTimers } from '@vitest/utils'
import { RealDate } from '../integrations/mock/date'
import type { WorkerGlobalState } from '../types'

export const UNKNOWN_TEST_ID = '__vitest__unknown_test__'

function getTaskIdByStack(root: string) {
const stack = new Error('STACK_TRACE_ERROR').stack?.split('\n')

if (!stack)
return UNKNOWN_TEST_ID

const index = stack.findIndex(line => line.includes('at Console.value (node:internal/console/'))
const line = index === -1 ? null : stack[index + 2]

if (!line)
return UNKNOWN_TEST_ID

const filepath = line.match(/at\s(.*)\s?/)?.[1]

if (filepath)
return relative(root, filepath)

return UNKNOWN_TEST_ID
}

export function createCustomConsole(state: WorkerGlobalState) {
const stdoutBuffer = new Map<string, any[]>()
const stderrBuffer = new Map<string, any[]>()
const timers = new Map<string, { stdoutTime: number; stderrTime: number; timer: any }>()
const unknownTestId = '__vitest__unknown_test__'

const { setTimeout, clearTimeout } = getSafeTimers()

Expand Down Expand Up @@ -63,7 +85,7 @@ export function createCustomConsole(state: WorkerGlobalState) {

const stdout = new Writable({
write(data, encoding, callback) {
const id = state?.current?.id ?? unknownTestId
const id = state?.current?.id ?? getTaskIdByStack(state.ctx.config.root)
let timer = timers.get(id)
if (timer) {
timer.stdoutTime = timer.stdoutTime || RealDate.now()
Expand All @@ -84,7 +106,7 @@ export function createCustomConsole(state: WorkerGlobalState) {
})
const stderr = new Writable({
write(data, encoding, callback) {
const id = state?.current?.id ?? unknownTestId
const id = state?.current?.id ?? getTaskIdByStack(state.ctx.config.root)
let timer = timers.get(id)
if (timer) {
timer.stderrTime = timer.stderrTime || RealDate.now()
Expand Down
4 changes: 4 additions & 0 deletions test/setup/setupFiles/console-setup.ts
@@ -0,0 +1,4 @@
// eslint-disable-next-line no-console
console.log('setup')

console.error('setup')
19 changes: 19 additions & 0 deletions test/setup/tests/console-setup.test.ts
@@ -0,0 +1,19 @@
import { describe, expect, test } from 'vitest'

import { runVitest } from '../../test-utils'

async function run() {
return await runVitest({
include: ['tests/fixtures/console.test.ts'],
setupFiles: ['setupFiles/console-setup.ts'],
})
}

describe('setup files console', () => {
test('print stdout and stderr correctly', async () => {
const { stdout, stderr } = await run()
const filepath = 'setupFiles/console-setup.ts'
expect(stdout).toContain(`stdout | ${filepath}`)
expect(stderr).toContain(`stderr | ${filepath}`)
})
})
3 changes: 3 additions & 0 deletions test/setup/tests/fixtures/console.test.ts
@@ -0,0 +1,3 @@
import { test } from 'vitest'

test('empty', () => {})

0 comments on commit ec2e804

Please sign in to comment.