3

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?

Mohammad Fared
  • 588
  • 1
  • 7
  • 19
Sophie N
  • 31
  • 2

2 Answers2

1

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!

heisenberg
  • 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
0

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...

How to read xml file(toolsbox.xml) in React typescript

doublejosh
  • 5,548
  • 4
  • 39
  • 45