我可以用 JSDOM 欺骗 instanceof 吗?

Can I trick instanceof with JSDOM?

我有一个反应 class 我想测试,并且 class 在开始时有这个 if 检查:

if (!(root instanceof window.HTMLElement)) {
   throw new Error('No HTML element was supplied. );
}

我试图通过 jsdom 传递一个假元素,但它没有 'fool' instanceof 检查。

const doc = (new JSDOM()).window.document;
const root = doc.createElement("div");
const pizza = new Builder(root);
expect(pizza).toBeDefined();

我查看了传入的内容

if (!(root instanceof window.HTMLElement)) {
  console.log(Object.prototype.toString.call(root));
  console.log(typeof window.HTMLElement)
  console.log(typeof root)
  throw new Error('No HTML element was supplied. );
}

它看起来一点也不像 window.HTMLElement:

    console.log src/main.jsx:20
      [object HTMLDivElement]
    console.log src/main.jsx:21
      function
    console.log src/main.jsx:22
      object

我怎样才能模拟 window.HTMLElement 以便测试这个 class?

您可以通过将 window 的属性指定为 global 的属性来模拟它们。 JSDOM 的实例在分配全局 属性 和使用它创建元素之间需要相同,否则 HTMLElement 的实例也会不同。为了绕过这个限制,我们将其引用为在 beforeEach 中设置的单个变量 jsDomInstance,而不是实例化多个副本。

const { JSDOM } = require('jsdom')

const { instanceofCheck } = require('./instanceofCheck')
// const instanceofCheck = x => x instanceof window.HTMLElement

describe('JSDOM tests', () => {
    let jsDomInstance

    beforeEach(() => {
        jsDomInstance = new JSDOM()
        global.HTMLElement = jsDomInstance.window.HTMLElement
    })

    it('passes instanceof check', () => {
        expect(
            instanceofCheck(
                jsDomInstance.window.document.createElement('div')
            )
        ).toBe(true)
    })
})

Demo