admin管理员组文章数量:1418590
In my React code, I listen for a FocusEvent, and perform a check on the type of the element that is being focused:
function onBlur(event) {
if(event.relatedTarget instanceof HTMLInputElement) { /* ... */ }
}
This works fine. I just don't seem able to write a proper unit test for it though... I figured I'd be able to call the onBlur
method as follows:
onBlur({ relatedTarget: new HTMLInputElement() });
...but unfortunately, that results in an error:
TypeError: Illegal constructor
I'm using Jest and Enzyme (which I think uses jsdom?), if that matters.
How best to approach this?
In my React code, I listen for a FocusEvent, and perform a check on the type of the element that is being focused:
function onBlur(event) {
if(event.relatedTarget instanceof HTMLInputElement) { /* ... */ }
}
This works fine. I just don't seem able to write a proper unit test for it though... I figured I'd be able to call the onBlur
method as follows:
onBlur({ relatedTarget: new HTMLInputElement() });
...but unfortunately, that results in an error:
TypeError: Illegal constructor
I'm using Jest and Enzyme (which I think uses jsdom?), if that matters.
How best to approach this?
Share Improve this question asked Aug 30, 2017 at 8:02 VincentVincent 5,4457 gold badges46 silver badges63 bronze badges3 Answers
Reset to default 4Using this you can mock your element:
var a = document.createElement('input')
a instanceof HTMLInputElement // returns true
If you need to add more behaviour then you can just add it to object a.
This will evaluate to true
:
document.createElement('input') instanceof HTMLInputElement
One more approach is to change the way to test you input element. You can use tagName
which should be 'INPUT' string:
function onBlur(event) {
if(event.relatedTarget.tagName === 'INPUT') { /* ... */ }
}
onBlur({ relatedTarget: {tagName: 'INPUT'} });
本文标签: javascriptHow can I mock an instanceof testStack Overflow
版权声明:本文标题:javascript - How can I mock an `instanceof` test? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745297600a2652171.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论