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');
});
如何编写规范来测试何时单击 link 它调用 visitDestination
并确保 window.open == next
?当我尝试 运行 规范时,它会打开新的 window。
所以,window.open
是浏览器提供的方法。我不相信它会重置自身的价值。所以这个:
expect(window.open).toBe('http://www.example.com');
...无论如何都会失败。
您想要的是创建 window.open 方法的模拟:
spyOn(window, 'open')
这将允许您跟踪它何时 运行。它还会阻止 运行ning 中的实际 window.open
函数。所以当你运行测试时,新的window不会打开。
接下来你应该测试 window.open
方法是 运行:
expect(window.open).toHaveBeenCalledWith(next)
编辑:更多细节。如果你想测试 visitDestination 是否为 运行 那么你可以这样做:
spyOn(window, 'visitDestination').and.callThrough()
...
expect(window.visitDestination).toHaveBeenCalled()
.and.callThrough()
在这里非常重要。如果你不使用它,那么正常的 visitDestination
将被替换为一个什么都不做的 dummy/mock 函数。
在新版本的 jasmine(3.5) 中,上述解决方案不起作用。我发现了一些解决方法来修复新的 window 打开而 运行 测试用例。在调用 window.open(url,_blank);
之前添加以下代码行
window.open = function () { return window; }
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');
});
如何编写规范来测试何时单击 link 它调用 visitDestination
并确保 window.open == next
?当我尝试 运行 规范时,它会打开新的 window。
所以,window.open
是浏览器提供的方法。我不相信它会重置自身的价值。所以这个:
expect(window.open).toBe('http://www.example.com');
...无论如何都会失败。
您想要的是创建 window.open 方法的模拟:
spyOn(window, 'open')
这将允许您跟踪它何时 运行。它还会阻止 运行ning 中的实际 window.open
函数。所以当你运行测试时,新的window不会打开。
接下来你应该测试 window.open
方法是 运行:
expect(window.open).toHaveBeenCalledWith(next)
编辑:更多细节。如果你想测试 visitDestination 是否为 运行 那么你可以这样做:
spyOn(window, 'visitDestination').and.callThrough()
...
expect(window.visitDestination).toHaveBeenCalled()
.and.callThrough()
在这里非常重要。如果你不使用它,那么正常的 visitDestination
将被替换为一个什么都不做的 dummy/mock 函数。
在新版本的 jasmine(3.5) 中,上述解决方案不起作用。我发现了一些解决方法来修复新的 window 打开而 运行 测试用例。在调用 window.open(url,_blank);
window.open = function () { return window; }