Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for focus an AngularJS directive

Tags:

How can you test for focus in an AngularJS directive? I would expect the following to work:

describe('focus test', function(){     it('should focus element', function(){         var element = $('<input type="text" />');         // Append to body because otherwise it can't be foccused         element.appendTo(document.body);         element.focus();         expect(element.is(':focus')).toBe(true);     }); }); 

However, this only works in IE, it fails in Firefox and Chrome

Update: The solution by @S McCrohan works. Using this I created a 'toHaveFocus' matcher:

beforeEach(function(){     this.addMatchers({         toHaveFocus: function(){             this.message = function(){                 return 'Expected \'' + angular.mock.dump(this.actual) + '\' to have focus';             };              return document.activeElement === this.actual[0];         }     }); }); 

Which is used as follows:

expect(myElement).toHaveFocus(); 

Note that for focus related tests, the compiled element has to be attached to the DOM, which can be done like this:

myElement.appendTo(document.body); 
like image 650
Mark Lagendijk Avatar asked Sep 17 '13 12:09

Mark Lagendijk


People also ask

What is focus in AngularJS?

AngularJS ng-focus Directive The ng-focus directive tells AngularJS what to do when an HTML element gets focus. The ng-focus directive from AngularJS will not override the element's original onfocus event, both will be executed.

Is AngularJS code unit testable?

AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.

How do I run a unit test in AngularJS?

Load the Angular App beforeEach(module('MyApp')); //3. Describe the object by name describe('compute', function () { var compute; //4. Initialize the filter beforeEach(inject(function ($filter) { compute = $filter('compute', {}); })); //5. Write the test in the it block along with expectations.


1 Answers

Try 'document.activeElement' instead of ':focus'. I haven't tested it in karma, but $('document.activeElement') behaves as desired under standard jQuery.

like image 181
S McCrohan Avatar answered Nov 20 '22 17:11

S McCrohan