【问题标题】:How to test jQuery with Jasmine for $("#element-id") if used as $(this)如果用作 $(this),如何使用 Jasmine 为 $("#element-id") 测试 jQuery
【发布时间】:2012-02-29 19:32:41
【问题描述】:

我不知道如何为我的 JS 运行这个 Jasmine 测试,当然其他人也有这个问题。也许我做错了,或者不可能 - 我没有找到任何暗示。问题与以下事实有关 - 在 jQuery 中 - $(this) 与例如选择的元素不同。 $("#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) 也没有让我更进一步。

【问题讨论】:

    标签: jquery testing jasmine jasmine-jquery


    【解决方案1】:

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

    这是我想要使用 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)”。

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

    【讨论】:

    • 这可能无关,但我无法找到任何具体的帮助(或者不知道如何查看),我非常感谢一些帮助。我发布了一个问题,但没有收到任何答案。我有一个 ASP.NET 应用程序,它使用带有一些“运行服务器”的 aspx 页面。在这种情况下是否可以使用 jasmine-jquery 测试我的 UI?除了 j-j 我还需要什么工具?我需要有业力吗?还要别的吗?谢谢。
    • 很抱歉,在这里我无法为您提供帮助。我在源 JS 文件上完全离线运行测试,并在需要时模拟我的 HTML。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    相关资源
    最近更新 更多