Testing User Actions - J Query

Code that relies on actions initiated by the user can’t be tested by just calling a function. Usually an anonymous function is bound to an element’s event, e.g., a click, which has to be simulated.

You can trigger the event using jQuery’s trigger() method and test that the expected behavior occurred. If you don’t want the native browser events to be triggered, you can use triggerHandler() to just execute the bound event handlers. This is useful when testing a click event on a link, where trigger() would cause the browser to change the location, which is hardly desired behavior in a test.
Let’s assume we have a simple key logger that we want to test:

We can manually trigger a keypress event to see whether the logger is working:

If your event handler doesn’t rely on any specific properties of the event, you can just call .trigger(eventType). However, if your event handler does rely on specific properties of the event, you will need to create an event object using $.Event and set the necessary properties, as shown previously.
It’s also important to trigger all relevant events for complex behaviors such as dragging, which is comprised of mousedown, at least one mouse move, and a mouseup. Keep in mind that even some events that seem simple are actually compound; e.g., a click is really a mousedown, mouseup, and then click. Whether you actually need to trigger all three of these depends on the code under test. Triggering a click works for most cases.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics