Empty
Empty

Reputation: 350

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

Upvotes: 6

Views: 3307

Answers (1)

Daryn
Daryn

Reputation: 5107

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

Upvotes: 8

Related Questions