Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Karma Test Cases : focus event

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

like image 526
Empty Avatar asked Nov 15 '13 05:11

Empty


1 Answers

(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();
}
like image 121
Daryn Avatar answered Sep 29 '22 09:09

Daryn