問題描述
JS
var link = this.notificationDiv.getElementsByTagName('a')[0];
link.addEventListener('click', function (evt){
evt.preventDefault();
visitDestination(next);
}, false);
}
var visitDestination = function(next){
window.open(next)
}
規(guī)格
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');
});
如何編寫規(guī)范以測試何時單擊鏈接它調用 visitDestination
并確保 window.open == next
?當我嘗試運行規(guī)范時,它會打開新窗口.
How to write the spec to test for when link is clicked it calls visitDestination
and to ensures window.open == next
? When I try to run the spec it opens the new window.
推薦答案
所以,window.open
是瀏覽器提供的一個方法.我不相信它會重置自身的價值.所以這個:
So, window.open
is a method provided by the browser. I don't believe it resets the value of itself. So this:
expect(window.open).toBe('http://www.example.com');
...無論如何都會失敗.
... is going to fail no matter what.
你想要的是創(chuàng)建一個 window.open 方法的模擬:
What you want is to create a mock of the window.open method:
spyOn(window, 'open')
這將允許您跟蹤它的運行時間.它還將阻止實際的 window.open
函數(shù)運行.因此,運行測試時不會打開新窗口.
This will allow you to track when it has been run. It will also prevent the actual window.open
function from running. So a new window will not open when you run the test.
接下來您應該測試 window.open
方法是否已運行:
Next you should test that the window.open
method was run:
expect(window.open).toHaveBeenCalledWith(next)
更多細節(jié).如果您想測試是否已運行 visitDestination,那么您可以:
More detail. If you want to test that visitDestination has been run then you would do:
spyOn(window, 'visitDestination').and.callThrough()
...
expect(window.visitDestination).toHaveBeenCalled()
.and.callThrough()
在這里非常重要.如果您不使用它,那么普通的 visitDestination
將被替換為不執(zhí)行任何操作的虛擬/模擬函數(shù).
The .and.callThrough()
is really important here. If you don't use it then the normal visitDestination
will be replace with a dummy/mock function which does nothing.
這篇關于Jasmine.js 測試 - 窺探 window.open的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!