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

本文标签: javascriptHow can I mock an instanceof testStack Overflow