Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Ok, now I've got the solution to my problem. The solution is easy, the explanation not. I'll explain the solution from scratch.</p> <p>This is my Javascript code with jQuery that I want to test using jasmine-jquery:</p> <pre><code>$( "input.toggler" ).on( "click", function( e ) { [...] doSomethingWith( $(this) ); } ); </code></pre> <p>And now using Jasmine-jQuery I want to ensure that the JS function "doSomethingWith" gets called with the correct "$(this)".</p> <p>First one might think that $(this) === $( "input.toggler" ), but that is not true. Inside the callback function of the click handler, the $(this) jQuery uses is neither the jQuery object $( "input.toggler" ) nor the DOM element referenced by that object. As Remy Sharp explains in his really nice article "<a href="http://remysharp.com/2007/04/12/jquerys-this-demystified/" rel="nofollow">jQuery's this: demystified</a>", the "this" inside the callback function is the DOM element, but $(this) creates a jQuery object from that DOM element. And that is not identical to the jQuery object $( "input.toggler" ).</p> <p>So if you want to test this with Jasmine using the function "toHaveBeenCalledWith", you have to first extract the DOM element using either document.getElementById(...) or else document.getElementsByTagName(...)[INDEX] (where INDEX is the index of the element you want, since the latter function gives you an array of DOM elements), which is plain old Javascript. Then, when you have extracted the DOM element wanted, you have to create a jQuery-object from it by enclosing it in $( and ).</p> <p>My passing Jasmine-jQuery-test finally looks something like this (using Coffeescript):</p> <pre><code>it "does something with my input element", -&gt; 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 ) ) </code></pre> <p>So the "$(this)" from my Javascript code translates to "$(DOM_input_element)" in my Jasmine-jQuery test.</p> <p>Hopefully this helps you with your projects! It took me quite a while to figure this out.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload