I'm having a problem testing some javascript that uses window.DOMParser
const stripLink = (url) => {
const parser = new DOMParser()
const link = parser.parseFromString(unescape(url),
'text/html').querySelector('a')
return link ? link.getAttribute('href') : url
}
When tested in mocha it gives a warning.
node:22883) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: DOMParser is not defined
I'm guessing this is because there is no DOMParser in node. How do I get around this? I've tried various things like
var DOMParser = require('xmldom').DOMParser
sinon.stub(window, 'DOMParser', DOMParser)
Thinking that if I replace window.DOMParser with xmldom parser for the tests it should work, but it doesn't.
Any idea how to get this working?
Update: 2020/12/02
For modern versions of js
there is no longer a need to install the dependency. Using global.DOMParser = window.DOMParser
should be sufficient. Thanks @tony-gentilcore
Original Answer
There is another similar workaround. You need to install the following packages:
npm install jsdom jsdom-global --save-dev
Then make sure to run the following code in a setup.js
file or before the first test runs:
setup.js
require('jsdom-global')()
global.DOMParser = window.DOMParser
This will allow you to call DOMParser
from within your src
s files without extracting it from a global object.
File Structure
.
├── src
└── tests
├── setup.js
└── some-test.spec.js
Replacing
const parser = new DOMParser()
With
const parser = new window.DOMParser()
Did the trick. Seems JSDOM already supports DOMParser however you need to explicitly call window.DOMParser() in your code for it to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With