Testing Events with Jasmine and Prototype

I realize that Prototype may be a bit out of fashion since jQuery has seemingly become the dominant front-end Javascript extension library. I’ve got a project that has a pile of code already written with Prototype, and the idea of converting all that to jQuery just seems like a waste of time. So I’m persisting.

I recently moved that project from Blue-Ridge (now an unsupported basically defunct Javascript testing framework) to Jasmine of which I’m already a huge fan. I was happy to see that from the onset, Jasmine had no real issues with testing Prototype code. After adding the gem to the project, and running `jasmine init`, I had a setup that was including my source code and a place to put my specs. I added a masylum/jasmine-prototype which provides a couple Prototype matchers and functionality to load fixtures.

The first little hurdle I ran into was trying to fire an click to test it’s response. Prototype has a `fire()` method on element. But it only allows firing of custom events. To get around this, I added a couple little Jasmine helpers that allowed me to inspect events that have been bound on an element and fire them.

To use these, either copy the code into your SpecHelper.js file or add a new file and add that helper file to your jasmine.yml and you can start calling it in your tests with something like this:

  describe('close button', function() {
    it("removes the dialog from the DOM", function() {
      jasmine.triggerEvent('#fixture .the_open_window .close_btn', 'click');
      expect($$('#fixture .the_open_window')).toEqual([]);

PS. You’ll notice the _.each() methods here. If you are following along exactly, you’ll also need to include underscore.js.


2 thoughts on “Testing Events with Jasmine and Prototype

  1. I’m in the same situation : PrototypeJs legacy in a big project. I was wondering if you could share your custom helpers (they might help be to improve testing for some custom events)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s