2017-05-04 14 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あるとき。上書きされています。 bodyは今まで私は何をすべきか、常にピントが合っている、

var elementInFocus = $('<input>'); 
    this.elem.append(elementInFocus); 
    elementInFocus.triggerHandler('focus'); 
    elementInFocus.focus(); 

しかし、それは同じだ。私はまた、要素を作成し、それにフォーカスを設定しようとしています。

答えて

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

関連する問題