Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if my element has been focussed in a unit test

Tags:

I have the following directive to autofocus a field:

.directive('ngAutofocus', function ($timeout) {     return {         restrict: 'A',         link: function (scope, elm) {                 $timeout(function () {                 elm[0].focus();             });         }     }; } 

How would I unit test this? I tried several things like the following selector but they all return errors or false:

console.log($(elm[0]).is(':focus')); 

My unit test is set up like this:

elm = angular.element('<input type="text"  name="textfield1" ng-autofocus>'); $scope.$digest(); $compile(elm)($scope); 
like image 327
Maarten Avatar asked Mar 11 '14 15:03

Maarten


People also ask

How do you know if an element is focused angular?

hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.

What do you check in a unit test?

Unit tests should validate all of the details, the corner cases and boundary conditions, etc. Component, integration, UI, and functional tests should be used more sparingly, to validate the behavior of the APIs or application as a whole.

How do you read a unit test?

A unit test is a piece of a code (usually a method) that invokes another piece of code and checks the correctness of some assumptions afterward. If the assumptions turn out to be wrong, the unit test has failed. A unit is a method or function. The thing you'll write tests for is called the system under test (SUT).


2 Answers

I figured it out, and it was pretty obvious actually;

it('should set the focus on timeout', function () {     spyOn(elm[0],'focus');     $timeout.flush();     expect(elm[0].focus).toHaveBeenCalled(); }) 

My problem was two-fold:

  1. I wasn't calling the timeout flush function so timeout wasn't occuring, and
  2. I was trying to look at the focus attribute of the element whereas just looking at the call of the focus() function is much more like unit-testing. The focus attribute is something that really belongs to the e2e testing territory.
like image 66
Maarten Avatar answered Nov 23 '22 18:11

Maarten


You can use document.activeElement to check focus. The only downside being that the HTML needs to be added to the document body for this to work.

https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement

like image 45
Hanne Olsen Avatar answered Nov 23 '22 18:11

Hanne Olsen