Note: the suggested link is an answer to a question about a service, and doesn't give a clear explanation on how to solve this issue
I'm trying to setup a karma test for my simple (and working) AngularJS autofocus
directive:
app.directive('autofocus', function ($timeout) {
return {
replace: false,
link: function (scope, element, attr) {
scope.$watch(attr.autofocus,
function (value) {
if (value) {
$timeout(function () {
element[0].focus();
console.log('focus called');
});
}
}
);
}
};
});
This is my current test:
describe('The autofocus directive', function () {
var timeout;
beforeEach(module('myApp'));
beforeEach(inject(function($timeout) {
timeout = $timeout;
}));
it('should set focus to first autofocus element', function () {
var form = angular.element('<form />');
var input1 = angular.element('<input type="text" name="first" />');
var input2 = angular.element('<input type="text" name="second" autofocus="true" />');
form.append(input1);
form.append(input2);
spyOn(input2[0], 'focus');
timeout.flush();
expect(input2[0].focus).toHaveBeenCalled();
});
This is the (FAILED) output from karma
:
$ node_modules/karma/bin/karma start test/karma.conf.js
INFO [karma]: Karma v0.12.23 server started at http:// localhost:8080/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.8 (Linux)]: Connected on socket U34UATs8jZDPB74AXpqR with id 96802943
PhantomJS 1.9.8 (Linux): Executed 0 of 20 SUCCESS (0 secs / 0 secs)
PhantomJS 1.9.8 (Linux) The autofocus directive should set focus to first autofocus element FAILED
Expected spy focus to have been called.
PhantomJS 1.9.8 (Linux): Executed 20 of 20 (1 FAILED) (0.156 secs / 0.146 secs)
Just adding
input[0].focus();
after spyOn(input[0], 'focus')
the test succeeds, of course, but it's not what I want...
The final question is: How do I karma-test a directive which sets focus to an element ?