jasmine-waituntil.js 1.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

// Takes a latch function and optionally timeout and error message.
// Polls the latch function until the it returns true or the maximum timeout expires
// whichever comes first.
(function(root, factory) {
    /* jshint strict: false */
    factory(root, root.jQuery);
}((function() {
    /* jshint strict: false */
    return this;
}()), function(window, $) {
    'use strict';

    var MAX_TIMEOUT = jasmine.DEFAULT_TIMEOUT_INTERVAL;
    var realSetTimeout = setTimeout;
    var realClearTimeout = clearTimeout;
    jasmine.waitUntil = function(conditionalFn, maxTimeout, message) {
        var deferred = $.Deferred(),
            elapsedTimeInMs = 0,
            timeout;

        maxTimeout = maxTimeout || MAX_TIMEOUT;
        message = message || 'Timeout has expired';

        var fn = function() {
            elapsedTimeInMs += 50;
            if (conditionalFn()) {
                if (timeout) { realClearTimeout(timeout); }
                deferred.resolve();
            } else {
                if (elapsedTimeInMs >= maxTimeout) {
                    // explicitly fail the spec with the given message
                    fail(message); // jshint ignore:line

                    // clear timeout and reject the promise
                    realClearTimeout(timeout);
                    deferred.reject();

                    return;
                }
                timeout = realSetTimeout(fn, 50);
            }
        };

        realSetTimeout(fn, 50);
        return deferred.promise();
    };
}));