From 11c181e3aa7a7a7e70a4e62b67940e4d5fbe1326 Mon Sep 17 00:00:00 2001 From: Jacob Fulton Date: Tue, 30 Apr 2024 03:23:11 -0400 Subject: [PATCH] Handle case when testsuites is not the root element of the JUnit xml file (#85) * Update junit.ts * Update junit.test.ts --- __tests__/junit.test.ts | 12 ++++++++++++ src/junit.ts | 14 ++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/__tests__/junit.test.ts b/__tests__/junit.test.ts index aba6b00..72d580c 100644 --- a/__tests__/junit.test.ts +++ b/__tests__/junit.test.ts @@ -51,6 +51,18 @@ describe('parsing junit', () => { 'Parse JUnit report. Non-whitespace before first tag.\nLine: 0\nColumn: 1\nChar: b' ) }) + + test('should work with omitted parent testsuites element', async () => { + const xml = + '' + const junit = await parseJunit(xml) + + expect(junit?.skipped).toBe(0) + expect(junit?.errors).toBe(0) + expect(junit?.failures).toBe(0) + expect(junit?.tests).toBe(2) + expect(junit?.time).toBe(0.981) + }) }) describe('parse junit and check report output', () => { diff --git a/src/junit.ts b/src/junit.ts index 8f073d1..c357101 100644 --- a/src/junit.ts +++ b/src/junit.ts @@ -20,8 +20,18 @@ export async function parseJunit(xmlContent: string): Promise { return null } - const main = parsedJunit.testsuites['$'] - const testsuites = parsedJunit.testsuites.testsuite + /** + * Usually the root element of a JUnit XML file. Some tools leave out + * the element if there is only a single top-level element (which + * is then used as the root element). + */ + const main = parsedJunit.testsuites?.$ ?? parsedJunit.testsuite?.$ + const testsuites = parsedJunit.testsuites?.testsuite + ? parsedJunit.testsuites?.testsuite + : parsedJunit.testsuite + ? [parsedJunit.testsuite] + : null + const errors = testsuites ?.map((t: any) => Number(t['$'].errors))