Jasmine.js 测试 - 窥探 window.open

Jasmine.js Testing - spy on window.open(Jasmine.js 测试 - 窥探 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.createSpyObj with properties(jasmine.createSpyObj 与属性)
What#39;s a good way to reuse test code using Jasmine?(使用 Jasmine 重用测试代码的好方法是什么?)
Does Jasmine#39;s toThrow matcher require the argument to be wrapped in an anonymous function?(Jasmine 的 toThrow 匹配器是否需要将参数包装在匿名函数中?)
Jasmine - Spying on a method call within a constructor(Jasmine - 在构造函数中监视方法调用)
Getting requirejs to work with Jasmine(让 requirejs 与 Jasmine 一起工作)
How can I spy on a getter property using jasmine?(如何使用 jasmine 监视 getter 属性?)