I want to perform unit tests with jest to transform an xml file into json. I created in my folder an example.xml file but I don't know how to import it in my test.js file Does anyone have an idea?
-
check out https://www.npmjs.com/package/xml2js for XML parsing. – LostJon Dec 22 '20 at 14:54
-
1I don't believe that will work, the error occurs during the import... `SyntaxError: Unexpected token '<'` – doublejosh Feb 17 '21 at 19:11
2 Answers
For example, if you want to load ./sample.xml
:
<retrieveCustomer><id>39399444</id></retrieveCustomer>
Here's the code to load from file:
var fs = require('fs'),
xml2js = require('xml2js');
var parser = new xml2js.Parser();
(async function () {
fs.readFile(__dirname + '/sample.xml', function(err, data) {
parser.parseString(data, function (err, result) {
console.dir(result);
console.log(typeof result);
console.log('Done');
});
});
}())
and here's the printed result:
$ node index.js
{ retrieveCustomer: { id: [ '39399444' ] } }
object
Done
You might not need to import it as an object (like parseString
does here), but if you want to import it as raw, you can use fs.readFile
then you stream the output to the program you want to test.
require('file.xml')
won't work because it only can be used to load and run Javascript files or to read and parse JSON files. It is not for loading other file format.
Hope this helps!

- 812
- 5
- 7
-
Not the answer I was hoping for, but it is what I expected. I'm dealing with legacy code that was made to work without tests. Bringing tests in just uncovered all the issues it had, one being the direct import of xml files, which work with typescript if you declare '*xml' global type >.> Anyways, thx! – Sebastien De Varennes Jul 24 '23 at 13:48
Jest doesn't know how to deal with any file types beyond JS. You must use a "transformer" to load and manipulate other types. You'll also need to update jest.config.js
to point such files to your transformer.
Update jest config --> https://github.com/facebook/jest/issues/2663
For TypeScript you also need @types/XML.d.ts
, details here...

- 5,548
- 4
- 39
- 45
-
Would be really helpful if you could provide a transformer example instead of simply linking to an issue related to a commonly used transformer. – Sebastien De Varennes Jul 18 '23 at 16:02