Jasmine.js Testing - spy on window.open(Jasmine.js 测试 - 窥探 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Jasmine.js 测试 - 窥探 window.open
基础教程推荐
- 我什么时候应该在导入时使用方括号 2022-01-01
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06