Erik A. Hanson's Weblog

Firing mouse events in tests

Posted: January 1st, 2008    Tags: Javascript, JsUnit, Unit Testing, Web development

The Bad News

Sending mouse events such as click and mouseover in JsUnit tests can be really hard.

More Bad News

Prototype doesn’t make it any easier. Sam Stephenson says:

We would very much like to support it in the future. It’s fairly complicated to implement native event firing across all supported browsers, so in 1.6.0, fire works with custom events only.

YUI To The Rescue

YAHOO.util.UserActions can simulate some user actions. Unfortunately, calls to YUI can look a bit clunky in a Prototype-heavy codebase:

var element = new Element("div").insert("Hi");
var offset = element.cumulativeOffset();
YAHOO.util.UserAction.click(element, { shiftKey: true });

YUI + Prototype FTW

A little mixin magic:

Element.addMethods({
  simulateClick: YAHOO.util.UserAction.click.bind(YAHOO.util.UserAction),
  simulateDblClick: YAHOO.util.UserAction.dblclick.bind(YAHOO.util.UserAction),
  simulateMousedown: YAHOO.util.UserAction.mousedown.bind(YAHOO.util.UserAction),
  simulateMouseup: YAHOO.util.UserAction.mouseup.bind(YAHOO.util.UserAction),
  simulateMouseover: YAHOO.util.UserAction.mouseover.bind(YAHOO.util.UserAction),
  simulateMouseout: YAHOO.util.UserAction.mouseout.bind(YAHOO.util.UserAction),
  simulateMousemove: YAHOO.util.UserAction.mousemove.bind(YAHOO.util.UserAction)
});

and now our test code looks nicer:

var element = new Element("div").insert("Hi");
var offset = element.cumulativeOffset();
myElement.simulateClick({ shiftKey: true });


Leave a Reply

About Me

I'm a software developer and consultant in San Francisco. I mostly develop web apps in Javascript, Java and Rails. There's a little more about me on my LinkedIn profile.

Recent Projects

wshlst.com: a group-oriented wish list website.

BoardsConsult​/​RotationTracker: a site to help medical residents prepare for the U.S. Medical Licensing Exam, and a related site to help medical schools evaluate and track the progress of the residents in their programs.

Jobs

I moderate a few completely free jobs mailing lists with RSS feeds and zero spam: XP jobs, Rails jobs and Mac development jobs. Also, my pals at Pivotal Labs have agile Rails and Java job openings.

Plug: Web Hosting

Looking for cheap shared web hosting and/or domain registration? I've been using DreamHost for years and I've been very happy with them. They offer tons of disk space and bandwidth, one-click installation for apps like WordPress and Gallery, unlimited domains, thousands of email accounts, private domain registration, and more. They are also a nice bunch of folks, not some big dumb company.