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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 javascript 认为文档“准备好"之前,如何让How can I get my jasmine tests fixtures to load before the javascript considers the document to be quot;readyquot;?(在 javascript 认为文档“准备好
jasmine 运行和等待实际上是做什么的?What do jasmine runs and waitsFor actually do?(jasmine 运行和等待实际上是做什么的?)
如何提供模拟文件来更改 <input type='filHow to provide mock files to change event of lt;input type=#39;file#39;gt; for unit testing(如何提供模拟文件来更改 lt;input type=filegt; 的事
如何使用 Jasmine 对链式方法进行单元测试How to unit test a chained method using Jasmine(如何使用 Jasmine 对链式方法进行单元测试)
如何将 $rootScope 注入 AngularJS 单元测试?How do I inject $rootScope into an AngularJS unit test?(如何将 $rootScope 注入 AngularJS 单元测试?)
Jasmine - 如何监视函数中的函数调用?Jasmine - How to spy on a function call within a function?(Jasmine - 如何监视函数中的函数调用?)