Firing mouse events in tests

January 2, 2008 Pivotal Labs

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();, { shiftKey: true });

YUI + Prototype FTW

A little mixin magic:

  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 });

About the Author


CPU Leak
CPU Leak

I just had to quit Firefox for the umpteenth time because it was taking up 25% of my CPU and 1.5 GB of virt...

Introducing RR
Introducing RR

I'm pleased to introduce a new Test Double (or mock) framework named RR, which is short for Double Ruby. ...

SpringOne 2021

Register Now