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'} });
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745297601a4621235.html
评论列表(0条)