监视 Jasmine 中的 JQuery 选择器

发布于 2024-10-22 04:07:59 字数 501 浏览 2 评论 0原文

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

我的规范是:

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

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

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

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

});

在我的 specrunner.html 中,我有:

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

不幸的是,规范失败了:

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

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.

My spec is:

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

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

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

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

});

In my specrunner.html I have:

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

Unfortunately the spec fails with:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

携余温的黄昏 2024-10-29 04:08:00

我编写了一个辅助函数,它接受 id/值对数组。

var jasminTestHelper = {
    spyOnValAndFake : function(obj) {
        var i, j;
        spyOn($.fn, 'val').andCallFake(function() {
            for ( i = 0, j = obj.length; i < j; i++) {
                if (this.selector === '#' + obj[i][0]) {
                    return obj[i][1];
                }
            }
        })
    }
}

每对告诉 faker 函数哪个 id,如果使用 id 选择器调用 jQuery-val() 函数,则应返回哪个值。它的使用方式如下:

jasminTestHelper.spyOnValAndFake([["id1", "value1"], ["id2", "value2"]]);

如果在被测函数中调用 $('#id1').val(),则假函数返回 value1,如果 $('#id2').val() 被调用,它返回 value2。所以你不需要摆弄 DOM,你只需模拟 jQuery-val() 函数并模拟返回值。其他 jQuery 函数可能会以同样的方式进行模拟。

I wrote a helper-function, which accepts an array of id/value-pairs.

var jasminTestHelper = {
    spyOnValAndFake : function(obj) {
        var i, j;
        spyOn($.fn, 'val').andCallFake(function() {
            for ( i = 0, j = obj.length; i < j; i++) {
                if (this.selector === '#' + obj[i][0]) {
                    return obj[i][1];
                }
            }
        })
    }
}

Each pair tells the faker-function for which id, which value should be returned if the jQuery-val()-function is called with the id-selector. It is used like this:

jasminTestHelper.spyOnValAndFake([["id1", "value1"], ["id2", "value2"]]);

If $('#id1').val() is called in your function under test, the fake-function returns value1, if $('#id2').val() is called it returns value2. So you don't need to fiddle with the DOM, you just mock the jQuery-val()-function and simulate return-values. Other jQuery-functions could probably mocked the same way.

嗫嚅 2024-10-29 04:08:00

我认为我的茉莉花版本(2.0.3)发生了变化,因此 Alex York 的解决方案并没有按原样工作,但肯定给了我一条路径。这是工作规范
这里要测试的 jquery 代码

$('someSelector').data('someAttribute').enable();

是它的 jasmine 规范部分

var mockJqueryObject = { enable:function(){},disable:function(){}};
//this mocks the .data('someAttribute') in above code.
spyOn($.fn, "data").and.returnValue(mockSelectBoxObject); 

更细粒度的规范可以使用另一级别的模拟作为

spyOn(mockJqueryObject,"enable")
spyOn(mockJqueryObject,"disable")

I think there is a change in my jasmine version (2.0.3), hence the solution by Alex York didn't work as is, but definitely gave me a path. So here is the working spec
jquery code which is to be tested

$('someSelector').data('someAttribute').enable();

here is the jasmine spec part of it

var mockJqueryObject = { enable:function(){},disable:function(){}};
//this mocks the .data('someAttribute') in above code.
spyOn($.fn, "data").and.returnValue(mockSelectBoxObject); 

A more granular spec could use another level of mock as

spyOn(mockJqueryObject,"enable")
spyOn(mockJqueryObject,"disable")
入画浅相思 2024-10-29 04:07:59

这行是错误的:

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

Jasmine 的间谍功能需要两个参数。第一个是现有的对象。第二个是字符串形式的函数名称。您正确地将函数名称作为字符串(“val”)传递,但没有将现有对象作为第一个参数传递。

$("#Something")

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

$

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

$.fn

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

$("#Something")

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

这将起作用:

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");
});

This line is wrong:

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

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")

...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")

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

This will work:

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");
});
何止钟意 2024-10-29 04:07:59

似乎我找到了很好的解决方案

    it "should open past statuses", ->
      # We can't use $('.past') here cause each time $('.past') called it returns different objects
      # so we need to store spy in variable
      showSpy = spyOn($.fn, 'show')
      # do the stuff
      $('.show-past').click()
      # then check if 'show' action was called
      expect($.fn.show).toHaveBeenCalled()
      # and if it realy our object
      expect(showSpy.mostRecentCall.object.selector).toEqual('.past')

这不是基于您的代码,但我希望这可以帮助某人。是的,还有 CoffeScript 中的示例。

Seems like I found good solution

    it "should open past statuses", ->
      # We can't use $('.past') here cause each time $('.past') called it returns different objects
      # so we need to store spy in variable
      showSpy = spyOn($.fn, 'show')
      # do the stuff
      $('.show-past').click()
      # then check if 'show' action was called
      expect($.fn.show).toHaveBeenCalled()
      # and if it realy our object
      expect(showSpy.mostRecentCall.object.selector).toEqual('.past')

This is not based on your code but i hope this can help someone. And, yes, example in CoffeScript.

停滞 2024-10-29 04:07:59

问题是对 $ 的两次调用返回两个不同的 jQuery 包装节点。

这应该有效:

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

  // var node = $("Something");
  // spyOn(node, 'val').andReturn('bar');

  // expect(node.val()).toEqual('bar');
  var node = $("Something");
  spyOn(node, 'val').and.returnValue('bar');

  expect(node.val()).toEqual('bar');
});

下次,Jasmine 邮件列表上的帮助会更普遍:[email protected] ]

The problem is that the two calls to $ return two different jQuery-wrapped nodes.

This should work:

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

  // var node = $("Something");
  // spyOn(node, 'val').andReturn('bar');

  // expect(node.val()).toEqual('bar');
  var node = $("Something");
  spyOn(node, 'val').and.returnValue('bar');

  expect(node.val()).toEqual('bar');
});

Next time, help is more prevalent on the Jasmine mailing list: [email protected].

夏有森光若流苏 2024-10-29 04:07:59

您可以创建自己的假 DOM 元素,然后像往常一样使用 $('#elementid')[0]

addFakeElementWithId = function (elementId) {
      var fake = document.createElement("div");
      fake.setAttribute("id", elementId);
      document.body.appendChild(fake);
   };

You could create your own fake DOM element and then use $('#elementid')[0] as usual

addFakeElementWithId = function (elementId) {
      var fake = document.createElement("div");
      fake.setAttribute("id", elementId);
      document.body.appendChild(fake);
   };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文