Riina
Riina

Reputation: 530

Using DOMParser in javascript testing with mocha and JSDOM

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?

Upvotes: 6

Views: 9664

Answers (2)

Dov Benyomin Sohacheski
Dov Benyomin Sohacheski

Reputation: 7732

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 srcs files without extracting it from a global object.

File Structure

.
├── src
└── tests
    ├── setup.js
    └── some-test.spec.js

Upvotes: 10

Riina
Riina

Reputation: 530

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.

Upvotes: 4

Related Questions