问题
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?
回答1:
In the past I wrote similar tests using document.activeElement to verify that an element received focus.
来源:https://stackoverflow.com/questions/24196072/how-to-test-focus-in-angularjs