javascript - 我可以用 JSDOM 欺骗 instanceof 吗?
问题描述
我有一个我想测试的反应类,如果在开始时检查这个类:
if (!(root instanceof window.HTMLElement)) {
throw new Error('No HTML element was supplied. );
}
我试图传递一个假元素,jsdom
但它并没有“欺骗”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
以便我可以测试这个类?
解决方案
window
您可以通过将它们分配为 的属性来模拟 的属性global
。will的实例JSDOM
在分配全局属性和使用它创建元素之间需要相同,否则实例HTMLElement
也会不同。为了解决这个限制,我们将其引用为中jsDomInstance
设置的单个变量beforeEach
,而不是实例化多个副本。
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)
})
})
推荐阅读
- javascript - Jquery - 允许表单提交和覆盖 preventDefault()?
- php - PHP两次向数据库提交条目
- java - 如何使用 java 在 Android 上检查密码学
- visual-c++ - 在 VIsual Studio 中跟踪代码流
- r - 如何在 R 中的 Vector 中对连续日期进行分组?
- youtube-api - YouTube 数据 API 频道列表未返回有效频道 ID 的结果
- reactjs - setting variables in a map function
- c++ - 为什么每次运行程序都会得到相同的随机数?
- vue.js - nuxt js中的自定义指令
- r - 在 tmap 中使用希腊字母(在 R 中)