Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 227
Riina Avatar asked Dec 14 '22 00:12

Riina


2 Answers

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
like image 87
Dov Benyomin Sohacheski Avatar answered Mar 16 '23 00:03

Dov Benyomin Sohacheski


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.

like image 41
Riina Avatar answered Mar 16 '23 01:03

Riina