javascript - How can I mock an `instanceof` test? - Stack Overflow

In my React code, I listen for a FocusEvent, and perform a check on the type of the element that is bei

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 badges
Add a ment  | 

3 Answers 3

Reset to default 4

Using 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'} });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745297601a4621235.html

相关推荐

  • javascript - How can I mock an `instanceof` test? - Stack Overflow

    In my React code, I listen for a FocusEvent, and perform a check on the type of the element that is bei

    12小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信