2017-05-04 170 views
2

我有以下功能:模拟document.activeElement在茉莉花测试

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

我遇到了一些麻烦,这太,一个可能的解决方案(为我工作)是添加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(); 
+0

我想这一点,但它不适用于我:( – stinaq