Manage requested UI click events in jQuery
I have a <input type="checkbox" /> that has a click handler associated with it through the jQuery .click function. Then he performs some calculations depending on his state:
$(':checkbox').click(function () { if (this.checked) { console.log("ACTIVE"); } else { console.log("INACTIVE"); } }); That all is well in the user interface, however, in my unit tests, I want to simulate a click on this element and make sure that the correct code is running.
$(testElement).click(); The problem is that the handler is called before the default browser action, so the values โโof this.checked are reversed. That is, it does not change the checked attribute until my handler is executed.
Is there any way around this? Can another event be linked? Is there any other way to trigger clicks programmatically?
By looking at this blog post , you can get the behavior you are looking at by following these steps:
$( ":checkbox" )[ 0 ].checked = !$( ":checkbox" )[ 0 ].checked; $(":checkbox" ).triggerHandler( "click" ); And with triggerHandler() you will fire events related only to jQuery, not the default.
Sample jsfiddle code.
Why load your unit tests when testing jQuery? Use the code directly in anonymous functions for worldly things, and for more important things, use a separate function that can be tested separately.
Something like that:
$(':checkbox').click(function () { checkboxClickHandler($(this)); }); And in unit test:
checkboxClickHandler($(':checkbox')); And your function:
function checkboxClickHandler(element) { alert(element.is(':checked')); }