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);
hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.
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.
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).
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:
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
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