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

查看:24
本文介绍了在 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" />

不幸的是规范失败了:

应该能够模拟 DOM 调用 Expected '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.

$

...是一个现有的对象.

...is an existing object.

$.fn

...是一个现有的对象.

...is an existing object.

$("#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天全站免登陆