Jasmine.js测试 - 窥探window.open

时间:2016-09-20 20:44:40

标签: javascript jasmine jasmine-jquery

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?当我尝试运行规范时,它会打开新窗口。

2 个答案:

答案 0 :(得分:11)

因此,window.open是浏览器提供的方法。我不相信它会重置自身的价值。所以这个:

expect(window.open).toBe('http://www.example.com');  

......无论如何都会失败。

你想要的是创建一个window.open方法的模拟:

spyOn(window, 'open')

这将允许您跟踪它何时运行。它还会阻止实际的window.open函数运行。因此,运行测试时将无法打开新窗口。

接下来,您应该测试window.open方法是否已运行:

expect(window.open).toHaveBeenCalledWith(next)

编辑:更详细。如果您想测试visitDestination已经运行,那么您可以这样做:

spyOn(window, 'visitDestination').and.callThrough()

...

expect(window.visitDestination).toHaveBeenCalled()

.and.callThrough()在这里非常重要。如果你不使用它,那么普通的visitDestination将被替换为无效的虚拟/模拟函数。

答案 1 :(得分:0)

在新版本的jasmine(3.5)中,上述解决方案不起作用。我发现有一些解决方法可以在运行测试用例时修复打开的新窗口。在调用您的window.open(url,_blank);

之前,在下面的代码行中添加
 window.open = function () { return window; }
相关问题