Posted over 6 years ago. Visible to the public. Linked content.

Testing setTimeout and setInterval with Jasmine

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

Copy
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(); });

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:

Copy
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.

Flaky tests are tests that sometimes fail for no obvious reason. They are the plague of many end-to-end (E2E) test suites that automate the browser through tools like Capybara and Selenium.

Join our free training event and learn to fix any flaky test suite, even in large legacy applications.

Owner of this card:

Avatar
Henning Koch
Last edit:
almost 6 years ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more