我有以下功能:
function focusIsNotInInput() {
// If the element currently in focus is of a certain type, then the key handler shouldn't run
var currentlyInFocus = $window.document.activeElement;
var blacklist = ['INPUT', 'TEXTAREA', 'BUTTON', 'SELECT', 'IFRAME', 'MD-OPTION'];
return !blacklist.some(function (nodeName) {
return nodeName === currentlyInFocus.nodeName;
});
}
我需要模拟当前关注的元素是指定类型之一,但无法使其工作。
我尝试过注入窗口,如下所示:
beforeEach(function() {
var $windowMock;
inject(function(_$window_) {
$windowMock = _$window_;
$windowMock.document.activeElement.nodeName = 'INPUT';
});
});
但是当上面的代码运行时,活动元素始终是body
。它被覆盖了。我也尝试过创建一个元素并将注意力集中在它上面:
var elementInFocus = $('<input>');
this.elem.append(elementInFocus);
elementInFocus.triggerHandler('focus');
elementInFocus.focus();
但是它是一样的,body
始终是焦点,我做什么。
答案 0 :(得分:0)
我也遇到了一些麻烦,一个可能的解决方案(对我有用)就是添加一个spyOn(element, 'focus')
- 这里有一个参考:How do I check if my element has been focussed in a unit test
我成功的解决方案:
const htmlItem = fixture.nativeElement;
const searchBar = htmlItem.querySelector('.search-box');
let focusSpy = spyOn(searchBar, 'focus');
searchBar.focus();
expect(focusSpy).toHaveBeenCalled();