如果用作$(this),如何使用Jasmine for $(“#element-id”)测试jQuery

时间:2012-02-29 19:32:42

标签: jquery testing jasmine jasmine-jquery

我不知道如何为我的JS运行这个Jasmine测试,当然其他人也有这个问题。也许我做错了或者也许这是不可能的 - 我没有找到任何暗示。这个问题与以下事实有关 - 在jQuery中 - $(this)与例如选择的元素不同。 $( “#这-ID”):

使用Javascript:

[..]
$("#button-id").on("click", function(e) { callSomeFunctionWith( $(this) ); } );

Jasmine-Test(CoffeeScript):

[..]
spyOn some.object, "callSomeFunctionWith"
spyOnEvent( $("#button-id"), 'click' )

$("#button-id").trigger( "click" )
expect( some.object.callSomeFunctionWith ).toHaveBeenCalledWith( $("#button-id") )

不幸的是,这个测试失败了(有任何变化,比如在我的Jasmine测试中首先将ref存储在变量中),因为函数不是用$(“#button-id”)调用的,而是用$调用(这个)和$(this)!= $(“#button-id”)。

有谁能告诉我如何完成这项测试?我很失落。即使Remy Sharp's great article on jQuery and $(this)也没有让我更进一步。

1 个答案:

答案 0 :(得分:4)

好的,现在我已经解决了我的问题。解决方案很简单,解释不是。我将从头开始解释解决方案。

这是我想用jasmine-jquery测试的jQuery javascript代码:

$( "input.toggler" ).on( "click", function( e ) {
  [...]
  doSomethingWith( $(this) );
} );

现在使用Jasmine-jQuery我想确保JS功能" doSomethingWith"使用正确的" $(this)"。

进行调用

第一个人可能认为$(this)=== $(" input.toggler"),但事实并非如此。 在click处理程序的回调函数中,$(this)jQuery使用的既不是jQuery对象$(" input.toggler"),也不是该对象引用的DOM元素。 正如雷米夏普在他非常好的文章" jQuery's this: demystified"," this"回调函数内部是DOM元素,但是$(this)从该DOM元素创建一个jQuery对象。这与jQuery对象$(" input.toggler")不完全相同。

因此,如果你想使用函数" toHaveBeenCalledWith"使用Jasmine测试它,你必须首先使用document.getElementById(...)或者document.getElementsByTagName(..)来提取DOM元素。 。)[INDEX](其中INDEX是你想要的元素的索引,因为后一个函数给你一个DOM元素数组),这是普通的旧Javascript。 然后,当你提取了想要的DOM元素时,你必须通过将它包含在$(和)中来创建一个jQuery对象。

我的传递Jasmine-jQuery测试最终看起来像这样(使用Coffeescript):

it "does something with my input element", ->
  DOM_input_element = document.getElementsByTagName( "input" )[0] # Choose the correct DOM element here

  spyOn myobject.functions, "doSomethingWith"
  spyOnEvent( $( 'input.toggler' ), 'click' )

  [...]

  $( 'input.toggler' ).trigger( 'click' )

  # Check for changes after click:
  expect( myobject.functions.doSomethingWith ).toHaveBeenCalledWith( $( DOM_input_element ) )

所以" $(this)"从我的Javascript代码转换为" $(DOM_input_element)"在我的Jasmine-jQuery测试中。

希望这可以帮助您完成项目!我花了很长时间来弄明白这一点。