Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jasmine 2 plug in to re-enable waitsFor and runs functionality
// This is the equivalent of the old waitsFor/runs syntax
// which was removed from Jasmine 2
waitsForAndRuns = function(escapeFunction, runFunction, escapeTime) {
// check the escapeFunction every millisecond so as soon as it is met we can escape the function
var interval = setInterval(function() {
if (escapeFunction()) {
clearMe();
runFunction();
}
}, 1);
// in case we never reach the escapeFunction, we will time out
// at the escapeTime
var timeOut = setTimeout(function() {
clearMe();
runFunction();
}, escapeTime);
// clear the interval and the timeout
function clearMe(){
clearInterval(interval);
clearTimeout(timeOut);
}
};
@abreckner

This comment has been minimized.

Show comment
Hide comment
@abreckner

abreckner May 9, 2014

Jasmine 2.0 removed waitsFor and runs (http://jasmine.github.io/1.3/introduction.html#section-Asynchronous_Support) and replaced them with a done callback syntax. (http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support).

This is fine for AJAX calls, but sometimes you might actually want to test other asynchronous functionality outside of the AJAX scope in code that does not use promises or deferreds (such as image loading for example).

You can use setTimeout, but this lacks the polling function of waitsFor and will slow down your test suite.

Example

If your class was

Button = function(){
  this.imageLoaded = false;
}

Button.prototype.loadImage = function(src) {
  var image = new Image();
  image.src = src;
  image.onload = function() {
    this.imageLoaded = true;
    this.stuffToDoAfterLoading();
  }
}

Button.prototype.stuffToDoAfterLoading = function(){
  // do stuff
}

Then you could test it in the following manner

  describe("#loadButton", function() {
    it("should wait until the image has loaded to do stuff", function(done) {

      var button = new Button();
      spyOn(button, 'stuffToDoAfterLoading');
      button.loadImage('/assets/button.png');

      waitsForAndRuns(function() {
        return button.imageLoaded;
      }, function() {
        expect(button.stuffToDoAfterLoading).toHaveBeenCalled();
        done();
      }, 500);

    });
  });
Owner

abreckner commented May 9, 2014

Jasmine 2.0 removed waitsFor and runs (http://jasmine.github.io/1.3/introduction.html#section-Asynchronous_Support) and replaced them with a done callback syntax. (http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support).

This is fine for AJAX calls, but sometimes you might actually want to test other asynchronous functionality outside of the AJAX scope in code that does not use promises or deferreds (such as image loading for example).

You can use setTimeout, but this lacks the polling function of waitsFor and will slow down your test suite.

Example

If your class was

Button = function(){
  this.imageLoaded = false;
}

Button.prototype.loadImage = function(src) {
  var image = new Image();
  image.src = src;
  image.onload = function() {
    this.imageLoaded = true;
    this.stuffToDoAfterLoading();
  }
}

Button.prototype.stuffToDoAfterLoading = function(){
  // do stuff
}

Then you could test it in the following manner

  describe("#loadButton", function() {
    it("should wait until the image has loaded to do stuff", function(done) {

      var button = new Button();
      spyOn(button, 'stuffToDoAfterLoading');
      button.loadImage('/assets/button.png');

      waitsForAndRuns(function() {
        return button.imageLoaded;
      }, function() {
        expect(button.stuffToDoAfterLoading).toHaveBeenCalled();
        done();
      }, 500);

    });
  });
@dprothero

This comment has been minimized.

Show comment
Hide comment
@dprothero

dprothero Jan 29, 2015

This is great. Just upgraded to Jasmine 2.0 and this helped a lot. Thanks!

dprothero commented Jan 29, 2015

This is great. Just upgraded to Jasmine 2.0 and this helped a lot. Thanks!

@borntorun

This comment has been minimized.

Show comment
Hide comment
@borntorun

borntorun Apr 23, 2015

Yes this is great... saved my day!
Thanks

(I'm testing a component that uses another component (that I not control) that makes in its inside an ajax call and then acts (the results being tested) on the component ... and simple the tests/expectations were evaluated too soon...)

borntorun commented Apr 23, 2015

Yes this is great... saved my day!
Thanks

(I'm testing a component that uses another component (that I not control) that makes in its inside an ajax call and then acts (the results being tested) on the component ... and simple the tests/expectations were evaluated too soon...)

@SimenB

This comment has been minimized.

Show comment
Hide comment
@SimenB

SimenB Aug 10, 2015

@abreckner Could you publish this to npm (with a module wrapping)?

SimenB commented Aug 10, 2015

@abreckner Could you publish this to npm (with a module wrapping)?

@Aaronius

This comment has been minimized.

Show comment
Hide comment
@Aaronius

Aaronius Aug 12, 2015

Thanks for this. This got me started and I reworked it to my liking. Here's another variation if anyone is interested:

/**
 * Polls an escape function. Once the escape function returns true, executes a run function.
 * @param {Function} escapeFunction A function that will be repeatedly executed and should return
 * true when the run function should be called.
 * @param {number} checkDelay Number of milliseconds to wait before checking the escape function
 * again.
 * @returns {{then: Function}} The run function should be registered via the then method.
 */
window.waitUntil = function(escapeFunction, checkDelay) {
  var _runFunction;

  var interval = setInterval(function() {
    if (escapeFunction()) {
      clearInterval(interval);

      if (_runFunction) {
        _runFunction();
      }
    }
  }, checkDelay || 1);

  return {
    then: function(runFunction) {
      _runFunction = runFunction;
    }
  };
};

Usage:

waitUntil(function() { return true }).then(function() { // do my thing });

Aaronius commented Aug 12, 2015

Thanks for this. This got me started and I reworked it to my liking. Here's another variation if anyone is interested:

/**
 * Polls an escape function. Once the escape function returns true, executes a run function.
 * @param {Function} escapeFunction A function that will be repeatedly executed and should return
 * true when the run function should be called.
 * @param {number} checkDelay Number of milliseconds to wait before checking the escape function
 * again.
 * @returns {{then: Function}} The run function should be registered via the then method.
 */
window.waitUntil = function(escapeFunction, checkDelay) {
  var _runFunction;

  var interval = setInterval(function() {
    if (escapeFunction()) {
      clearInterval(interval);

      if (_runFunction) {
        _runFunction();
      }
    }
  }, checkDelay || 1);

  return {
    then: function(runFunction) {
      _runFunction = runFunction;
    }
  };
};

Usage:

waitUntil(function() { return true }).then(function() { // do my thing });
@SimenB

This comment has been minimized.

Show comment
Hide comment
@SimenB

SimenB Mar 2, 2016

I published a module doing this. Quickly hacked together, but it works 😄
http://npm.im/wait-until-promise

SimenB commented Mar 2, 2016

I published a module doing this. Quickly hacked together, but it works 😄
http://npm.im/wait-until-promise

@RoyTinker

This comment has been minimized.

Show comment
Hide comment
@RoyTinker

RoyTinker Sep 8, 2017

This is really useful for testing a Promise library.

RoyTinker commented Sep 8, 2017

This is really useful for testing a Promise library.

@kumar155

This comment has been minimized.

Show comment
Hide comment
@kumar155

kumar155 Dec 20, 2017

@SimenB, @RoyTinker
i'm getting this error 'expect' was used when there was no current spec, this could be because an asynchronous test timed out

it('validate target view data for application option auto gaps', () => {
	// component mount
        const Component = mount(
            h(Provider, { store }, [
                h(IntlProvider, { locale: 'en' },
                    h(RDSMContainer),
                )],
           ));
     Component.find('.dropdown-choice').first().simulate('click');
     waitUntil(function () {
            // update the component
            Component.update();
            return Component.find('.targetView').length > 0
        }).then((result) => {
            const TargetComponent = RDSMComponent.find(TargetView);
            expect(TargetComponent.instance().state.applications.length > 0).toBe(true);
      },3000);
});

kumar155 commented Dec 20, 2017

@SimenB, @RoyTinker
i'm getting this error 'expect' was used when there was no current spec, this could be because an asynchronous test timed out

it('validate target view data for application option auto gaps', () => {
	// component mount
        const Component = mount(
            h(Provider, { store }, [
                h(IntlProvider, { locale: 'en' },
                    h(RDSMContainer),
                )],
           ));
     Component.find('.dropdown-choice').first().simulate('click');
     waitUntil(function () {
            // update the component
            Component.update();
            return Component.find('.targetView').length > 0
        }).then((result) => {
            const TargetComponent = RDSMComponent.find(TargetView);
            expect(TargetComponent.instance().state.applications.length > 0).toBe(true);
      },3000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment