jQuery provides a isTrigger
property which allows us to know if the event was a "real event" or was it only "triggered".
$(ele).on("click", function(e){
if(e.isTrigger){
// this event was only triggered, not a real event
}else{
// this was a real event
}
})
For unit-testing purposes, is there a way to trigger
a event and somehow overwrite the isTrigger
property.. and in the event callback still behave (by having isTrigger === false
) as if it was a real click event..
Was trying the following code:
var triggerClick = jQuery.Event("click", {
isTrigger:false,
data:{
isTrigger:false
}
but it doesn't seem to pass it correctly..
$('button'). click(function(event, wasTriggered) { if (wasTriggered) { alert('triggered in code'); } else { alert('triggered by mouse'); } }); $('button').
To check if event is triggered by a human with JavaScript, we can use the isTrusted property. to check if the event is triggered by a human in our event handler callback. e is the event object and it had the isTrusted property. If isTrusted is true , then the event is triggered by a human.
jQuery trigger() MethodThe trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.
trigger( "click" ); As of jQuery 1.3, . trigger() ed events bubble up the DOM tree; an event handler can stop the bubbling by returning false from the handler or calling the . stopPropagation() method on the event object passed into the event.
How about the native way, avoiding the jQuery isTrigger altogether:
function simulateClick(elem) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, elem,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
if (document.createEvent) {
elem.dispatchEvent(evt);
} else {
elem.fireEvent("on" + evt.eventType, evt); // support for IE crap
}
}
To use it you'd just do:
$(ele).on("click", function(e){
if(e.isTrigger){
// this event was only triggered, not a real event
console.log('triggered');
}else{
// this was a real event
console.log('clicked');
}
});
simulateClick(ele);
FIDDLE
If you are concerned about whether or not an event was trigger by the user or by code, perhaps you should extract a method and call that method directly. You can then add a userTriggered
parameter and pass true or false.
$(ele).on("click", function(e){
doWork($(this), e, true);
}
doWork($(ele), null, false);
function doWork(item, e, userTriggered)
{
if(userTriggered) {
}
else {
}
}
Then when you test your doWork method, you can pass in userTriggered
as true or false to test the desired behavior. This also eliminates the dependency of browser behavior from your test, which is a good thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With