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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)