I am testing a focus event in angularjs using karma test cases. But the element is not getting focused. Right after I do element.focus() and check if the element is focused, I get false. And document.activeElement at that point is the whole body.
Please suggest a solution. Thanks
(This answer inspired by Testing for focus an AngularJS directive)
You need to add your element to the document body in order for document.activeElement to play with it.
Before you call element.focus()
, do this:
element.appendTo(document.body);
Also, if you're doing this in unit tests I would recommend that you remove the element after the test, otherwise each test will add another element to the body (and it could affect your other tests' results).
afterEach(function () {
element.remove();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With