Skip to content

Commit 6f74e5e

Browse files
gbleuclaude
andauthored
fix(junit): include unhandled errors in JUnit XML report (#10244)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 511c092 commit 6f74e5e

7 files changed

Lines changed: 260 additions & 26 deletions

File tree

‎packages/vitest/src/node/reporters/junit.ts‎

Lines changed: 109 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import type { Task } from '@vitest/runner'
2+
import type { SerializedError } from '@vitest/utils'
23
import type { Vitest } from '../core'
4+
import type { ErrorOptions } from '../logger'
35
import type { Reporter } from '../types/reporter'
46
import type { TestModule } from './reported-tasks'
57
import { existsSync, promises as fs } from 'node:fs'
@@ -138,6 +140,15 @@ type TaskWithMeta = Task & {
138140
_suitename?: string
139141
}
140142

143+
/**
144+
* Runtime additions on top of {@link SerializedError}: `type` is set by
145+
* {@link state.catchError}, `VITEST_TEST_PATH` by the runtime error catcher.
146+
*/
147+
type UnhandledError = SerializedError & {
148+
type?: string
149+
VITEST_TEST_PATH?: string
150+
}
151+
141152
function flattenTasks(task: Task, baseName = '', suiteName = '', ancestorSeparator = ' > '): TaskWithMeta[] {
142153
if (task.type === 'suite') {
143154
const newBase = baseName ? `${baseName}${ancestorSeparator}${task.name}` : task.name
@@ -384,25 +395,9 @@ export class JUnitReporter implements Reporter {
384395
if (task.result?.state === 'fail') {
385396
const errors = task.result.errors || []
386397
for (const error of errors) {
387-
await this.writeElement(
388-
'failure',
389-
{
390-
message: error?.message,
391-
type: error?.name,
392-
},
393-
async () => {
394-
if (!error || !this.options.stackTrace) {
395-
return
396-
}
397-
398-
const result = this.ctx.logger.formatError(error, {
399-
project: this.ctx.getProjectByName(task.file?.projectName ?? ''),
400-
})
401-
await this.baseLog(
402-
escapeXML(stripVTControlCharacters(result.output.trim())),
403-
)
404-
},
405-
)
398+
await this.writeErrorElement('failure', error, {
399+
project: this.ctx.getProjectByName(task.file?.projectName ?? ''),
400+
})
406401
}
407402
}
408403
},
@@ -440,7 +435,86 @@ export class JUnitReporter implements Reporter {
440435
.replace(/\{title\}/g, () => vars.title)
441436
}
442437

443-
async onTestRunEnd(testModules: ReadonlyArray<TestModule>): Promise<void> {
438+
private async writeErrorElement(
439+
elementName: 'failure' | 'error',
440+
error: SerializedError | undefined,
441+
errorOptions: ErrorOptions,
442+
): Promise<void> {
443+
await this.writeElement(
444+
elementName,
445+
{
446+
message: error?.message,
447+
type: error?.name,
448+
},
449+
async () => {
450+
if (!error || !this.options.stackTrace) {
451+
return
452+
}
453+
const result = this.ctx.logger.formatError(error, errorOptions)
454+
await this.baseLog(
455+
escapeXML(stripVTControlCharacters(result.output.trim())),
456+
)
457+
},
458+
)
459+
}
460+
461+
private async writeUnhandledErrorsTestsuite(
462+
unhandledErrors: ReadonlyArray<UnhandledError>,
463+
testModules: ReadonlyArray<TestModule>,
464+
): Promise<void> {
465+
await this.writeElement(
466+
'testsuite',
467+
{
468+
name: 'vitest unhandled errors',
469+
timestamp: new Date().toISOString(),
470+
hostname: this.options.hostname || hostname(),
471+
tests: unhandledErrors.length,
472+
failures: 0,
473+
errors: unhandledErrors.length,
474+
skipped: 0,
475+
time: '0',
476+
},
477+
async () => {
478+
// Stable order across runs — workers/projects report errors concurrently.
479+
const sortedErrors = [...unhandledErrors].sort((a, b) => {
480+
const ka = `${a.VITEST_TEST_PATH ?? ''}\0${a.type ?? ''}\0${a.name ?? ''}\0${a.message ?? ''}`
481+
const kb = `${b.VITEST_TEST_PATH ?? ''}\0${b.type ?? ''}\0${b.name ?? ''}\0${b.message ?? ''}`
482+
return ka < kb ? -1 : ka > kb ? 1 : 0
483+
})
484+
for (const error of sortedErrors) {
485+
const errorTitle = error.type || error.name || 'Unhandled Error'
486+
// Only attribute when the path resolves to exactly one module — when
487+
// multiple projects share a file, errors lack a project identifier and
488+
// we can't disambiguate without one (tracked for follow-up).
489+
const matches = error.VITEST_TEST_PATH
490+
? testModules.filter(m => m.task.filepath === error.VITEST_TEST_PATH)
491+
: []
492+
const owningModule = matches.length === 1 ? matches[0] : undefined
493+
await this.writeElement(
494+
'testcase',
495+
{
496+
classname: 'vitest unhandled errors',
497+
file: this.options.addFileAttribute && error.VITEST_TEST_PATH
498+
? relative(this.ctx.config.root, error.VITEST_TEST_PATH)
499+
: undefined,
500+
name: error.message ? `${errorTitle}: ${error.message}` : errorTitle,
501+
time: '0',
502+
},
503+
async () => {
504+
await this.writeErrorElement('error', error, {
505+
project: owningModule?.project,
506+
})
507+
},
508+
)
509+
}
510+
},
511+
)
512+
}
513+
514+
async onTestRunEnd(
515+
testModules: ReadonlyArray<TestModule>,
516+
unhandledErrors: ReadonlyArray<UnhandledError> = [],
517+
): Promise<void> {
444518
const files = testModules.map(testModule => testModule.task)
445519
const separator = this.options.ancestorSeparator ?? ' > '
446520

@@ -516,18 +590,25 @@ export class JUnitReporter implements Reporter {
516590
name: this.options.suiteName || 'vitest tests',
517591
tests: 0,
518592
failures: 0,
519-
errors: 0, // we cannot detect those
593+
errors: unhandledErrors.length,
520594
time: 0,
521595
},
522596
)
597+
stats.tests += unhandledErrors.length
523598

524-
await this.writeElement('testsuites', { ...stats, time: executionTime(stats.time) }, async () => {
525-
for (let i = 0; i < transformed.length; i++) {
526-
const file = transformed[i]
599+
// Plain byte compare (not localeCompare) so output is identical across machines and ICU versions.
600+
const orderedSuites = transformed
601+
.map((file, i) => {
527602
const filename = relative(this.ctx.config.root, file.filepath)
528603
// resolveSuiteNameTemplate needs the original file (before task flattening) to
529604
// search for top-level describe blocks, so pass files[i] directly.
530605
const suiteName = this.resolveSuiteNameTemplate(files[i], filename)
606+
return { file, filename, suiteName }
607+
})
608+
.sort((a, b) => a.suiteName < b.suiteName ? -1 : a.suiteName > b.suiteName ? 1 : 0)
609+
610+
await this.writeElement('testsuites', { ...stats, time: executionTime(stats.time) }, async () => {
611+
for (const { file, filename, suiteName } of orderedSuites) {
531612
await this.writeElement(
532613
'testsuite',
533614
{
@@ -545,6 +626,10 @@ export class JUnitReporter implements Reporter {
545626
},
546627
)
547628
}
629+
630+
if (unhandledErrors.length) {
631+
await this.writeUnhandledErrorsTestsuite(unhandledErrors, testModules)
632+
}
548633
})
549634

550635
if (this.reportFile) {
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { it } from 'vitest'
2+
3+
it('triggers a rejection from project 1', async () => {
4+
void Promise.reject(new Error('rejection from space-1'))
5+
await new Promise(resolve => setTimeout(resolve, 50))
6+
})
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { it } from 'vitest'
2+
3+
it('triggers a rejection from project 2', async () => {
4+
void Promise.reject(new Error('rejection from space-2'))
5+
await new Promise(resolve => setTimeout(resolve, 50))
6+
})
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { defineConfig } from 'vitest/config'
2+
3+
export default defineConfig({
4+
test: {
5+
projects: ['space-1', 'space-2'],
6+
},
7+
})
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { it } from 'vitest'
2+
3+
it('triggers two rejections and one uncaught exception', async () => {
4+
void Promise.reject(new Error('first rejection'))
5+
void Promise.reject(new Error('second rejection'))
6+
setTimeout(() => {
7+
throw new Error('uncaught timer')
8+
}, 0)
9+
await new Promise(resolve => setTimeout(resolve, 50))
10+
})

‎test/e2e/test/reporters/__snapshots__/junit.test.ts.snap‎

Lines changed: 98 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,55 @@ Error: afterAll error
5959
"
6060
`;
6161
62+
exports[`emits one <testcase> per unhandled error and titles them by error.type 1`] = `
63+
"<?xml version="1.0" encoding="UTF-8" ?>
64+
<testsuites name="vitest tests" tests="4" failures="0" errors="3" time="...">
65+
<testsuite name="multi.test.ts" timestamp="..." hostname="..." tests="1" failures="0" errors="0" skipped="0" time="...">
66+
<testcase classname="multi.test.ts" name="triggers two rejections and one uncaught exception" time="...">
67+
</testcase>
68+
</testsuite>
69+
<testsuite name="vitest unhandled errors" timestamp="..." hostname="..." tests="3" failures="0" errors="3" skipped="0" time="...">
70+
<testcase classname="vitest unhandled errors" name="Uncaught Exception: uncaught timer" time="...">
71+
<error message="uncaught timer" type="Error">
72+
Error: uncaught timer
73+
❯ Timeout._onTimeout multi.test.ts:7:11
74+
75+
This error originated in &quot;multi.test.ts&quot; test file. It doesn&apos;t mean the error was thrown inside the file itself, but while it was running.
76+
The latest test that might&apos;ve caused the error is &quot;triggers two rejections and one uncaught exception&quot;. It might mean one of the following:
77+
- The error was thrown, while Vitest was running this test.
78+
- If the error occurred after the test had been completed, this was the last documented test before it was thrown.
79+
</error>
80+
</testcase>
81+
<testcase classname="vitest unhandled errors" name="Unhandled Rejection: first rejection" time="...">
82+
<error message="first rejection" type="Error">
83+
Error: first rejection
84+
❯ multi.test.ts:4:23
85+
86+
This error originated in &quot;multi.test.ts&quot; test file. It doesn&apos;t mean the error was thrown inside the file itself, but while it was running.
87+
The latest test that might&apos;ve caused the error is &quot;triggers two rejections and one uncaught exception&quot;. It might mean one of the following:
88+
- The error was thrown, while Vitest was running this test.
89+
- If the error occurred after the test had been completed, this was the last documented test before it was thrown.
90+
</error>
91+
</testcase>
92+
<testcase classname="vitest unhandled errors" name="Unhandled Rejection: second rejection" time="...">
93+
<error message="second rejection" type="Error">
94+
Error: second rejection
95+
❯ multi.test.ts:5:23
96+
97+
This error originated in &quot;multi.test.ts&quot; test file. It doesn&apos;t mean the error was thrown inside the file itself, but while it was running.
98+
The latest test that might&apos;ve caused the error is &quot;triggers two rejections and one uncaught exception&quot;. It might mean one of the following:
99+
- The error was thrown, while Vitest was running this test.
100+
- If the error occurred after the test had been completed, this was the last documented test before it was thrown.
101+
</error>
102+
</testcase>
103+
</testsuite>
104+
</testsuites>
105+
"
106+
`;
107+
62108
exports[`format error 1`] = `
63109
"<?xml version="1.0" encoding="UTF-8" ?>
64-
<testsuites name="vitest tests" tests="9" failures="8" errors="0" time="...">
110+
<testsuites name="vitest tests" tests="10" failures="8" errors="1" time="...">
65111
<testsuite name="error.test.ts" timestamp="..." hostname="..." tests="9" failures="8" errors="0" skipped="0" time="...">
66112
<testcase classname="error.test.ts" name="stack" time="...">
67113
<failure message="throwSimple" type="Error">
@@ -124,6 +170,18 @@ Error: throwSuite
124170
</failure>
125171
</testcase>
126172
</testsuite>
173+
<testsuite name="vitest unhandled errors" timestamp="..." hostname="..." tests="1" failures="0" errors="1" skipped="0" time="...">
174+
<testcase classname="vitest unhandled errors" name="Unhandled Rejection: throwSimple" time="...">
175+
<error message="throwSimple" type="Error">
176+
Error: throwSimple
177+
❯ throwSimple error.test.ts:44:9
178+
❯ error.test.ts:16:16
179+
❯ error.test.ts:16:28
180+
181+
This error originated in &quot;error.test.ts&quot; test file. It doesn&apos;t mean the error was thrown inside the file itself, but while it was running.
182+
</error>
183+
</testcase>
184+
</testsuite>
127185
</testsuites>
128186
"
129187
`;
@@ -157,3 +215,42 @@ __test_stderr__
157215
</testsuites>
158216
"
159217
`;
218+
219+
exports[`resolves unhandled errors to the owning project in a multi-project workspace 1`] = `
220+
"<?xml version="1.0" encoding="UTF-8" ?>
221+
<testsuites name="vitest tests" tests="4" failures="0" errors="2" time="...">
222+
<testsuite name="space-1/test/reject.test.ts" timestamp="..." hostname="..." tests="1" failures="0" errors="0" skipped="0" time="...">
223+
<testcase classname="space-1/test/reject.test.ts" file="space-1/test/reject.test.ts" name="triggers a rejection from project 1" time="...">
224+
</testcase>
225+
</testsuite>
226+
<testsuite name="space-2/test/reject.test.ts" timestamp="..." hostname="..." tests="1" failures="0" errors="0" skipped="0" time="...">
227+
<testcase classname="space-2/test/reject.test.ts" file="space-2/test/reject.test.ts" name="triggers a rejection from project 2" time="...">
228+
</testcase>
229+
</testsuite>
230+
<testsuite name="vitest unhandled errors" timestamp="..." hostname="..." tests="2" failures="0" errors="2" skipped="0" time="...">
231+
<testcase classname="vitest unhandled errors" file="space-1/test/reject.test.ts" name="Unhandled Rejection: rejection from space-1" time="...">
232+
<error message="rejection from space-1" type="Error">
233+
Error: rejection from space-1
234+
❯ test/reject.test.ts:4:23
235+
236+
This error originated in &quot;test/reject.test.ts&quot; test file. It doesn&apos;t mean the error was thrown inside the file itself, but while it was running.
237+
The latest test that might&apos;ve caused the error is &quot;triggers a rejection from project 1&quot;. It might mean one of the following:
238+
- The error was thrown, while Vitest was running this test.
239+
- If the error occurred after the test had been completed, this was the last documented test before it was thrown.
240+
</error>
241+
</testcase>
242+
<testcase classname="vitest unhandled errors" file="space-2/test/reject.test.ts" name="Unhandled Rejection: rejection from space-2" time="...">
243+
<error message="rejection from space-2" type="Error">
244+
Error: rejection from space-2
245+
❯ test/reject.test.ts:4:23
246+
247+
This error originated in &quot;test/reject.test.ts&quot; test file. It doesn&apos;t mean the error was thrown inside the file itself, but while it was running.
248+
The latest test that might&apos;ve caused the error is &quot;triggers a rejection from project 2&quot;. It might mean one of the following:
249+
- The error was thrown, while Vitest was running this test.
250+
- If the error occurred after the test had been completed, this was the last documented test before it was thrown.
251+
</error>
252+
</testcase>
253+
</testsuite>
254+
</testsuites>
255+
"
256+
`;

‎test/e2e/test/reporters/junit.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { runVitest, runVitestCli } from '#test-utils'
44
import { createFileTask } from '@vitest/runner/utils'
55
import { resolve } from 'pathe'
66
import { expect, test } from 'vitest'
7+
import { rolldownVersion } from 'vitest/node'
78

89
const root = resolve(import.meta.dirname, '../../fixtures/reporters')
910

@@ -122,7 +123,13 @@ test('options.suiteName changes name property', async () => {
122123
})
123124

124125
function stabilizeReport(report: string) {
125-
return report.replaceAll(/(timestamp|hostname|time)=".*?"/g, '$1="..."')
126+
let normalized = report.replaceAll(/(timestamp|hostname|time)=".*?"/g, '$1="..."')
127+
// rolldown's source map for the inline async IIFE on error.test.ts:16 anchors
128+
// one column later than rollup's; align to rollup so the snapshot stays bundler-agnostic.
129+
if (rolldownVersion) {
130+
normalized = normalized.replaceAll(' ❯ error.test.ts:16:29', ' ❯ error.test.ts:16:28')
131+
}
132+
return normalized
126133
}
127134

128135
function stabilizeReportWOTime(report: string) {
@@ -333,6 +340,22 @@ test('stackTrace set to false omits stack trace content from failure', async ()
333340
expect(xml).not.toContain('❯ error.test.ts')
334341
})
335342

343+
test('emits one <testcase> per unhandled error and titles them by error.type', async () => {
344+
const { stdout } = await runVitest({
345+
reporters: 'junit',
346+
root: './fixtures/reporters/unhandled-errors-multi',
347+
})
348+
expect(stabilizeReport(stdout)).toMatchSnapshot()
349+
})
350+
351+
test('resolves unhandled errors to the owning project in a multi-project workspace', async () => {
352+
const { stdout } = await runVitest({
353+
reporters: [['junit', { addFileAttribute: true }]],
354+
root: './fixtures/reporters/unhandled-errors-multi-project',
355+
})
356+
expect(stabilizeReport(stdout)).toMatchSnapshot()
357+
})
358+
336359
function executionTime(durationMS: number) {
337360
return (durationMS / 1000).toLocaleString('en-US', {
338361
useGrouping: false,

0 commit comments

Comments
 (0)