gpt4 book ai didi

jquery - 如果用作 $(this) 如何使用 Jasmine 测试 jQuery $ ("#element-id")

转载 作者:行者123 更新时间:2023-11-28 19:49:40 24 4
gpt4 key购买 nike

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

Javascript:

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

Jasmine 测试(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)没有让我更进一步。

最佳答案

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

这是我想使用 jasmine-jquery 测试的带有 jQ​​uery 的 Javascript 代码:

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

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

第一个可能认为 $(this) === $( "input.toggler"),但事实并非如此。在点击处理程序的回调函数中,jQuery 使用的 $(this) 既不是 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] 提取 DOM 元素(其中 INDEX 是您想要的元素的索引,因为后一个函数为您提供了一个 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)”。

希望这对您的项目有所帮助!我花了很长时间才弄明白这一点。

关于jquery - 如果用作 $(this) 如何使用 Jasmine 测试 jQuery $ ("#element-id"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com