【问题标题】:How to mock document.evaluate() and XPathResult in a mocha unit test?如何在 mocha 单元测试中模拟 document.evaluate() 和 XPathResult?
【发布时间】:2020-05-30 16:34:47
【问题描述】:

我有以下 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

有人可能有提示吗?谢谢。

【问题讨论】:

    标签: javascript dom xpath mocha.js jsdom


    【解决方案1】:

    jsdom 旁边添加jsdom-global(描述为here):

    npm i -D jsdom jsdom-global
    

    mocha 执行测试时注册jsdom-global

    mocha -r jsdom-global/register test/**/*.test.js
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-09
      • 2018-11-06
      • 2019-08-26
      • 2017-06-14
      • 1970-01-01
      • 2016-11-19
      • 2016-02-23
      • 1970-01-01
      相关资源
      最近更新 更多