This content originally appeared on DEV Community and was authored by Will Drygla
Have you ever checked an XML of test reports, and think that could be more info inside it?
Today I will show you an way to insert test context inside the XML of jest (you could use any XML)
In my article:

Test context: A powerfull way to debug our tests
Will Drygla ・ Feb 23
I use this XML on my pipelines, after test runs.
Steps:
While test run:
1.1 - Collect test context
1.2 - Save context to a JSON fileWhen tests are finished
2.1 - Read the json file
2.2 - Read the XML file
2.3 - Find failures on XML
2.4 - Find an context the matchs XML failure (I match then based on test name)
2.5 - Write XML with the test context
Step 1:
afterEach(async () => {
const { assertionCalls, numPassingAsserts, currentTestName } = expect.getState();
const failedTest = assertionCalls > numPassingAsserts;
if (failedTest) {
createContextJsonFile(currentTestName, testContext);
} });
Step 2:
2.1: For each JSON on the 'reports' folder, whe call the function that save the data to XML report:
jsonFiles.forEach((file) => {
const filePath = path.join(folderPath, file);
fs.readFile(filePath, 'utf8', (err, data) => {
const jsonData = JSON.parse(data);
saveJsonToXml(jsonData)
2.4: Find an failure that match our JSON test name and write test context to it:
let extraMessage = Context of test ${data.testName};
for (const key of Object.keys(data.context)) {
extraMessage = extraMessage.concat(\n${key}: ${JSON.stringify(data.context[key])});
}
let fileContent = fs.readFileSync(filePath, 'utf8');
const doc = new DOMParser().parseFromString(fileContent, 'text/xml');
const testCases = doc.getElementsByTagName('testcase');
for (let index = 0; index < testCases.length; index++) {
const testCase = testCases[index];
if (testCase.getAttribute('classname') === data.testName) {
const failureNode = testCase.getElementsByTagName('failure')[0];
if (failureNode) {
failureNode.textContent = failureNode.textContent + extraMessage;
2.5: Write the XML with addition of new content:
fileContent = new XMLSerializer().serializeToString(doc);
fs.writeFileSync(filePath, fileContent);
The result will be an XML like this:
This content originally appeared on DEV Community and was authored by Will Drygla

Will Drygla | Sciencx (2025-02-23T16:48:20+00:00) How to insert test context inside XML of jest. Retrieved from https://www.scien.cx/2025/02/23/how-to-insert-test-context-inside-xml-of-jest/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.