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?
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?
Share Improve this question edited Jun 15, 2018 at 3:41 Dov Benyomin Sohacheski 7,7428 gold badges41 silver badges66 bronze badges asked Mar 7, 2017 at 13:33 RiinaRiina 5301 gold badge8 silver badges19 bronze badges 1- Take a look at this answer: stackoverflow./a/55668667/6666348 – Kamran Taghaddos Commented May 15, 2022 at 12:07
2 Answers
Reset to default 10Update: 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.