Reputation: 171489
Consider the following skFocus
service:
angular.module('sk.focus', []).service('skFocus', function($timeout) {
return function(cssSelector) {
$timeout(function() {
var element = document.querySelectorAll(cssSelector);
if (element.length > 0) {
element[0].focus();
}
}, 100);
};
});
I'm trying to create a test for this service:
describe('Service: skFocus', function() {
beforeEach(module('sk.focus'));
var $window, $timeout, skFocus;
beforeEach(inject(function(_$window_, _$timeout_, _skFocus_) {
$window = _$window_;
$timeout = _$timeout_;
skFocus = _skFocus_;
angular.element(document.body).append('<input id="my-input-field" type="text">');
}));
it('Should set focus', function() {
skFocus('#my-input-field');
$timeout.flush();
var $inputElement = $window.jQuery('#my-input-field');
console.log($inputElement.length); // 1
expect($inputElement.is(':focus')).toBe(true); // Fails!!
});
});
Unfortunately, the test fails.
What am I doing wrong?
Upvotes: 2
Views: 4833
Reputation: 6837
I faced similar issue with focus
not being triggered. In my case problem was that I created HTML
template in memory const template = angular.element('<div><input type="text"></div>')
and didn't append it to document.body
.
After appending template
to the <body>
the focus
listener started to work.
Upvotes: 1
Reputation: 18194
In the past I wrote similar tests using document.activeElement to verify that an element received focus.
Upvotes: 2