Jasmine.js测试-在window.open上进行监视 [英] Jasmine.js Testing - spy on window.open
问题描述
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)
}
规范
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
?当我尝试运行规范时,它将打开新窗口.
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.
您想要的是创建window.open方法的模拟:
What you want is to create a mock of the window.open method:
spyOn(window, 'open')
这将允许您跟踪它何时运行.这也将阻止实际的window.open
函数运行.因此,运行测试时将不会打开新窗口.
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)
更多细节.如果您要测试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
将替换为不执行任何操作的虚拟/模拟功能.
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上进行监视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!