I have a method which uses DOMParser to parse a XML, like this:
this.parseXmlString = function(xmlDocStr) {
var xmlDoc;
var parser= new window.DOMParser();
xmlDoc = parser.parseFromString( xmlDocStr, "text/xml" );
// here I do some stuff with xmlDoc
return xmlDoc;
};
The problem is: when I try to make a unit test with Jest of this function window.DOMParser
is undefined. The test is as simple as:
expect(x2js.parseXmlString(xmlDocStr)).toMatchObject(expectedObject);
Is there any way I can use DOMParser from a Jest unit test?
You don't need to window
reference. Just use new DOMParser()...
. Make sure you have "testEnvironment": "jsdom"
in your Jest configuration (it should be the default though).
I've created an example here. https://repl.it/@ChrisPaton/FlusteredNearDecimal
You will also most likely need the latest version of Jest, as jsdom
only added support for DOMParser
and XMLSerializer
in late October.
Update
JSDom is not supported above v11 by Jest. You'll need to configure a custom environment for this. Here is a link to their documentation and here is a link to a custom jsdom environment that is easy to use. I hope this helps.