Read more

Testing setTimeout and setInterval with Jasmine

Henning Koch
April 29, 2015Software engineer at makandra GmbH

Jasmine has a jasmine.clock() helper Show archive.org snapshot that you can use to travel through time and trigger setTimeout and setInterval callbacks:

beforeEach(function() {
  timerCallback = jasmine.createSpy("timerCallback");
  jasmine.clock().install();
});

afterEach(function() {
  jasmine.clock().uninstall();
});

it("causes a timeout to be called", function() {
  setTimeout(function() {
    timerCallback();
  }, 100);

  expect(timerCallback).not.toHaveBeenCalled();

  jasmine.clock().tick(101);

  expect(timerCallback).toHaveBeenCalled();
});
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

If you actually want the test to wait out the timer, your example function needs to accept a done argument, which you then call when the test is expected to finish:

it("causes a timeout to be called", function(done) {
  setTimeout(function() {
    timerCallback();
  }, 100);
  setTimeout(function() {
    expect(timerCallback).toHaveBeenCalled();
    done();
  }, 101);
});

Needless to say the second test is much slower than the first test.

Posted by Henning Koch to makandra dev (2015-04-29 16:04)