RSe*_*ohn 5 testing jquery jasmine jasmine-jquery
我不知道如何为我的JS运行这个Jasmine测试,当然其他人也有这个问题.也许我做错了或者也许这是不可能的 - 我没有找到任何暗示.问题与以下事实有关 - 在jQuery中 - $(this)与例如$("#this-id")选择的元素不同:
使用Javascript:
[..]
$("#button-id").on("click", function(e) { callSomeFunctionWith( $(this) ); } );
Run Code Online (Sandbox Code Playgroud)
Jasmine-Test(CoffeeScript):
[..]
spyOn some.object, "callSomeFunctionWith"
spyOnEvent( $("#button-id"), 'click' )
$("#button-id").trigger( "click" )
expect( some.object.callSomeFunctionWith ).toHaveBeenCalledWith( $("#button-id") )
Run Code Online (Sandbox Code Playgroud)
不幸的是,这个测试失败了(有任何变化,例如在我的Jasmine测试中首先将ref存储在变量中),因为函数不是用$("#button-id")调用的,而是用$(this)调用,和$(this)!= $("#button-id").
谁能告诉我如何完成这个测试?我很失落.即使是Remy Sharp关于jQuery和$(这个)的精彩文章也没有让我更进一步.
好的,现在我已经找到了解决我的问题的方法。解决方案很简单,但解释却不简单。我将从头开始解释解决方案。
这是我的 jQuery Javascript 代码,我想使用 jasmine-jquery 进行测试:
$( "input.toggler" ).on( "click", function( e ) {
[...]
doSomethingWith( $(this) );
} );
Run Code Online (Sandbox Code Playgroud)
现在使用 Jasmine-jQuery 我想确保使用正确的“$(this)”调用 JS 函数“doSomethingWith”。
第一个可能认为 $(this) === $( "input.toggler" ),但事实并非如此。在点击处理程序的回调函数中,jQuery 使用的 $(this) 既不是 jQuery 对象 $( "input.toggler" ) 也不是该对象引用的 DOM 元素。正如 Remy Sharp 在他非常好的文章“ jQuery 的 this:揭秘”中所解释的那样,回调函数中的“this”是 DOM 元素,但是 $(this) 从该 DOM 元素创建一个 jQuery 对象。这与 jQuery 对象 $("input.toggler") 不同。
因此,如果您想使用 Jasmine 函数“toHaveBeenCalledWith”对此进行测试,则必须首先使用 document.getElementById(...) 或 document.getElementsByTagName(...)[INDEX] 提取 DOM 元素(其中 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 ) )
Run Code Online (Sandbox Code Playgroud)
因此,我的 Javascript 代码中的“$(this)”在我的 Jasmine-jQuery 测试中转换为“$(DOM_input_element)”。
希望这对您的项目有所帮助!我花了很长时间才弄清楚这一点。
| 归档时间: |
|
| 查看次数: |
4547 次 |
| 最近记录: |