2016-09-20 19 views
1

JSJasmine.js測試 - 對window.open

var link = this.notificationDiv.getElementsByTagName('a')[0]; 

link.addEventListener('click', function (evt){ 
    evt.preventDefault(); 
    visitDestination(next); 
    }, false); 
} 

var visitDestination = function(next){ 
    window.open(next) 
} 

規格

var next = "http://www.example.com" 

    it('should test window open event', function() { 

    var spyEvent = spyOnEvent('#link', 'click').andCallFake(visitDestination(next));; 
    $('#link')[0].click(); 
    expect('click').toHaveBeenTriggeredOn('#link'); 
    expect(spyEvent).toHaveBeenTriggered(); 

    expect(window.open).toBeDefined(); 
    expect(window.open).toBe('http://www.example.com');  
}); 

怎麼寫規範來測試諜當鏈接被點擊它調用visitDestination和確保window.open == next?當我嘗試運行規格時,它會打開新窗口。

回答

5

所以,window.open是瀏覽器提供的方法。我不相信它重置了它本身的價值。所以這個:

expect(window.open).toBe('http://www.example.com'); 

......無論如何都會失敗。

你需要的是創造window.open方法的模擬:

spyOn(window, 'open') 

這將允許你跟蹤時,它已經運行。它也將阻止實際的window.open函數運行。因此,當您運行測試時,新窗口不會打開。

接下來,你應該測試的window.open方法運行:

expect(window.open).toHaveBeenCalledWith(next) 

編輯:更多細節。如果你想測試visitDestination已運行,那麼你會怎麼做:

spyOn(window, 'visitDestination').and.callThrough() 

... 

expect(window.visitDestination).toHaveBeenCalled() 

.and.callThrough()是非常重要的位置。如果你不使用它,那麼正常的visitDestination將被替換爲不執行任何操作的虛擬/模擬功能。