如果用作$(this),如何使用Jasmine for $(“#element-id”)测试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)调用,和$(this)!= $(“#button-id”).

谁能告诉我如何完成这个测试?我很失落.甚至Remy Sharp’s great article on jQuery and $(this)也没有让我更进一步.

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

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

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

现在使用Jasmine-jQuery我想确保用正确的“$(this)”调用JS函数“doSomethingWith”.

一个人可能认为$(this)=== $(“input.toggler”),但事实并非如此.
在click处理程序的回调函数中,$(this)jQuery使用既不是jQuery对象$(“input.toggler”)也不是该对象引用的DOM元素.
正如Remy Sharp在他非常好的文章jQuery’s this: demystified”中解释的那样,回调函数中的“this”是DOM元素,但$(this)从该DOM元素创建了一个jQuery对象.这与jQuery对象$(“input.toggler”)不同.

因此,如果您想使用函数“toHaveBeenCalledWith”使用Jasmine进行测试,则必须首先使用document.getElementById(…)或document.getElementsByTagName(…)[INDEX](其中INDEX)提取DOM元素是你想要的元素的索引,因为后一个函数为你提供了一个DOM元素数组),这是一个简单的旧Javascript.
然后,当你提取了想要的DOM元素时,你必须通过将它封装在$(和)中来创建一个jQuery对象.

我传递的Jasmine-jQuery-test最终看起来像这样(使用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 ) )

所以我的Javascript代码中的“$(this)”在我的Jasmine-jQuery测试中转换为“$(DOM_input_element)”.

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

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: <span id=&quot...
jQuery 添加水印 <script src="../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...