2017-05-04 96 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