简体   繁体   English

在 mocha 和 JSDOM 的 javascript 测试中使用 DOMParser

[英]Using DOMParser in javascript testing with mocha and JSDOM

I'm having a problem testing some javascript that uses window.DOMParser我在测试一些使用 window.DOMParser 的 javascript 时遇到问题

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.在 mocha 中测试时,它会发出警告。

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.我猜这是因为 node.js 中没有 DOMParser 。 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.认为如果我用 xmldom 解析器替换 window.DOMParser 进行测试,它应该可以工作,但它没有。

Any idea how to get this working?知道如何让这个工作吗?

Update: 2020/12/02更新:2020/12/02

For modern versions of js there is no longer a need to install the dependency.对于现代版本的js ,不再需要安装依赖项。 Using global.DOMParser = window.DOMParser should be sufficient.使用global.DOMParser = window.DOMParser应该就足够了。 Thanks @tony-gentilcore谢谢@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文件中或在第一次测试运行之前运行以下代码:

setup.js设置.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.这将允许您从src文件中调用DOMParser ,而无需从全局对象中提取它。

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.似乎 JSDOM 已经支持 DOMParser 但是您需要在代码中显式调用 window.DOMParser() 才能使其工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM