我有以下 JavaScript 类包装 document.evaluate()
使用 XPath 选择 DOM 元素:
'use strict'
Object.defineProperty(exports, '__esModule', { value: true })
class ElementByXPath {
constructor(elementXPath) {
this.elementXPath = elementXPath
}
element(document) {
return document.evaluate(
this.elementXPath,
document.documentElement,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null,
).singleNodeValue
}
}
exports.ElementByXPath = ElementByXPath
以下用 mocha
编写的测试将验证方法 element()
:
describe('ElementByXPath function test', () => {
it('should return element of given XPath', () => {
const dom = new JSDOM(`<p id = "test-id"/p>`)
const result = new ElementByXpath('//*[@id="test-id"]').element(
dom.window.document,
)
expect(result.tagName).to.equal('P')
})
})
使用JSDOM我能够模拟 window
元素。不幸的是,我无法模拟 XPathResult
:
ReferenceError: XPathResult is not defined
有人可能有提示吗?谢谢。
最佳答案
在 jsdom
旁边添加 jsdom-global
(描述 here ):
npm i -D jsdom jsdom-global
当mocha
执行测试时注册jsdom-global
mocha -r jsdom-global/register test/**/*.test.js
关于javascript - 如何在 Mocha 单元测试中模拟 document.evaluate() 和 XPathResult?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60233741/