Mootools Event Spies for Jasmine Tests
JavaScript
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.gitignore
LICENSE
README.md
event-spies.js

README.md

MooTools Event Spies for Jasmine Tests

This is a Jasmine helper for testing MooTools events. It builds on the runs() and waitsFor() methods from Jasmine for handling asynchronous code.

See our introductory blog post for some background.

Installation

Copy event-spies.js to your Jasmine helpers directory (e.g. app/spec/javascripts/helpers/).

Usage:

In your Jasmine test, set up some event spies on the object that will trigger the events:

spyOnEvent(object, 'eventName');

Later, call the code that should trigger the event, in a runs block:

runs(function() {
    object.doSomething();
});

Then wait for the event to have been triggered (last argument is a timeout):

waitsForEvent(object, 'eventName', 500);

If you want to test side effects of the event, you will need to also put that in a runs block:

runs(function() {
    expect(object.state).toEqual('done');
});

You can retrieve the data of the last event (per event type) with

var data = lastEventData(object, 'eventName');
expect(data.foo).toEqual('bar');

You can also expect events to have been triggered or not:

expect(object).toHaveTriggered('working');
expect(object).toNotHaveTriggered('complete');

Example:

it("can submit to queued", function () {
    // Setup listening for the queued event
    spyOnEvent(order, 'queued');

    // Trigger a (mock) Ajax request
    runs(function() {
        jasmine.Ajax.stubRequest('/some/endpoint').andReturn({
            "status": 200,
            "contentType": 'application/json',
            "responseText": '{"status" : "queued", "job_id" : "foo"}'
        });
        order.submit();
    });

    // Expect the event to have been thrown within 500ms
    waitsForEvent(order, 'queued', 500);

    // Expect our code to have done the right thing with the event
    runs(function() {
        expect(jasmine.Ajax.requests.mostRecent().url).toEqual("/some/endpoint");
        expect(order.status).toEqual('queued');
        var data = lastEventData(order, 'queued');
        expect(data.job_id).toEqual("someId");
    });
});

Acknowledgements:

This was shameless copy-pasted inspired by and adapted from Luiz Ribeiro's jQuery implementation.