Search code examples
javascriptdomxpathmocha.jsjsdom

How to mock document.evaluate() and XPathResult in a mocha unit test?


I have following JavaScript class wrapping document.evaluate() selecting a DOM element using a XPath:

'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

Following test written in mocha shall verify the method 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')
  })
})

Using JSDOM I was able to mock the window element. Unfortunately, I cannot mock XPathResult:

ReferenceError: XPathResult is not defined

Has someone maybe a hint? Thanks.


Solution

  • Add jsdom-global next to jsdom (described here):

    npm i -D jsdom jsdom-global
    

    Register jsdom-global when mocha executes the tests

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