存根jQuery选择器调用? [英] Stub out a jQuery selector call?

查看:89
本文介绍了存根jQuery选择器调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力改进我的JavaScript单元测试。我有以下代码:

I'm trying to get better at unit testing my JavaScript. I have the following code:

var categoryVal = $('#category').val();
if (categoryVal === '') { 
    doSomething();
} 

我的测试跑步者没有 #category 在页面上输入,那么我将如何在这里存根/模拟jQuery选择器?我查看了 jasmin sinon 文档,但无法弄清楚如何让它们在这里工作,因为它们的存根操作对象, $ 是不是。

My test runner doesn't have the #category input on the page, so how would I stub/mock out the jQuery selector here? I've looked at both the jasmin and sinon documentation, but can't figure out how to get them to work here, since their stubs operate on objects, which $ is not.

推荐答案

这里的问题是 $()是使用方法 val()返回对象的函数。因此,您必须使用存根$()来返回具有方法val的存根对象。

The problem here is that $() is a function that returns an object with the method val(). So you have to stub $() to return a stubbed object having the method val.

$ = sinon.stub();
$.withArgs('#category').returns(sinon.stub({val: function(){}}));

但这里的主要错误是让你要测试的代码调用函数$()来创建新实例。为什么?最好的做法是在类中不创建新实例,而是将它们传递给构造函数。假设您有一个函数可以从输入中获取值,将其加倍,然后将其写回另一个:

But the main mistake here is to let the code you want to test call the function $() to create new instances. Why? Its best practice to create no new instances in your class, but to pass them into the constructor. Let's say you have function that will get a value out of an input, double it, and write it back to another:

function doubleIt(){
    $('#el2').val(('#el1').val() *2);
}

在这种情况下,您可以通过调用创建2个新对象$()。现在你必须存根 $()来返回一个模拟和一个存根。使用下一个示例,您可以避免这种情况:

In this case you create 2 new objects by calling $(). Now you have to stub $() to return a mock and a stub. Using the next example you can avoid this:

function doubleIt(el1, el2){
    el2.val(el1.val() *2);
}

虽然在第一种情况下你必须以存根$来返回存根,在第二种情况下,你可以很容易地将存根和间谍传递给你的函数。

While, in the first case you have to stub $ to return a stub, in the second case you can easily pass a stub and a spy into your function.

所以第二个的sinon测试看起来像这样:

So the sinon test for the second one would look like this:

var el1 =  sinon.stub({val: function(){}});
    el1.returns(2);

var el2 = sinon.spy({val: function(){}}, 'val')

doubleIt(el1, el2)

assert(el2.withArgs(4).calledOnce)

所以,因为这里没有dom元素,您只需测试应用程序逻辑,无需在应用程序中创建相同的dom。

So, as you have no dom elements here, you can simply test your application logic with no need to create the same dom as in your app.

这篇关于存根jQuery选择器调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆