How to insert test context inside XML of jest

Will Drygla - Feb 23 - - Dev Community

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:

I talk about test context, now, we will put this context inside the XML.

I use this XML on my pipelines, after test runs.

Steps:

  1. While test run:
    1.1 - Collect test context
    1.2 - Save context to a JSON file

  2. When 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:
the image shows an xml with addition of text context, generate using the script described on this post

. . . . . . .