在Jasmine中监视JQuery选择器 [英] Spying on JQuery Selectors in Jasmine

查看:151
本文介绍了在Jasmine中监视JQuery选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jasmine对一些JavaScript进行单元测试,并希望监视(模拟)由jQuery选择器访问的DOM元素。

I am unit testing some JavaScript with Jasmine and wish to spy on (mock) an element of the DOM that is accessed by a jQuery selector.

我的规范是:

it("should be able to mock DOM call", function() {

    spyOn($("#Something"), 'val').andReturn("bar");

    result = $("#Something").val();

    expect(result).toEqual("bar");

});

在我的specrunner.html中我有:

In my specrunner.html I have:

<input type="hidden" id="Something" value="foo" />

不幸的是,规格失败了:

Unfortunately the spec fails with:


应该能够模拟DOM调用预期'foo'等于'bar'。

should be able to mock DOM call Expected 'foo' to equal 'bar'.


推荐答案

这一行错了:

spyOn($("#Something"), 'val').andReturn("bar");

Jasmine的spyOn函数需要两个参数。第一个是现有对象。第二个是函数名称作为字符串。您正确地将函数名称作为字符串传递(val),但您没有将现有对象作为第一个参数传入。

Jasmine's spyOn function expects two parameters. The first is an existing object. The second is a function name as a string. You are correctly passing in the function name as a string ("val") but you are not passing in an existing object as the first parameter.

$("#Something")

...不是现有对象。它是jQuery选择器的结果(返回值)。更具体地说,它将返回一个表示匹配节点的jQuery对象 - 有点像结果数组。

...is not an existing object. It is the result (the return value) of a jQuery selector. More specifically, it will return a jQuery object representing the matched nodes - kind of like an array of results.

$

...是现有对象。

$.fn

...是现有对象。

$("#Something")

... 现有对象 - 它是 jQuery选择器的结果

...is not an existing object - it is the result of a jQuery selector.

这将有效:

it("should be able to mock DOM call", function () {
    //spyOn($.fn, "val").andReturn("bar"); //pre-jasmine 2.0 syntax
    spyOn($.fn, "val").and.returnValue("bar"); //Jasmine 2.0 Syntax
    var result = $("#Something").val();
    expect(result).toEqual("bar");
});

这篇关于在Jasmine中监视JQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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