Reputation: 1447
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?
Upvotes: 3
Views: 5411
Reputation: 282
On recent jest
version (>28) you just have to install jest-environment-jsdom
and change your test environment.
In package.json
"jest-environment-jsdom": "^29.7.0",
Then the environment either in the jest config file
testEnvironment: 'jsdom',
or by adding a @jest-environment
docblock at the top of the file for all tests in that file:
/**
* @jest-environment jsdom
*/
https://jestjs.io/docs/configuration#testenvironment-string
Upvotes: 0
Reputation: 5233
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.
Upvotes: 9