mardi 7 mars 2017

testing javascript 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?

Aucun commentaire:

Enregistrer un commentaire