Click here to Skip to main content
13,000,324 members (76,946 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


Posted 21 Aug 2014

Mock the window.setTimeout in a Jasmine Test to Avoid Waiting

, 21 Aug 2014
Rate this:
Please Sign up or sign in to vote.
Mock the window.setTimeout in a Jasmine test to avoid waiting

Originally posted on

Jasmine has a clock mocking feature, but I was unable to make it work in a function that I’m calling and want to test. The example only shows using clock for a setTimeout in the spec tests and I couldn’t find a good example. Here is my current and slightly limited approach.

If we have a method we want to test:

var test = function(){
        var self = this;
        self.timeoutWasCalled = false;
        self.testWithTimeout = function(){
             self.timeoutWasCalled = true;
           }, 6000);

Here’s my testing code:

var realWindowSetTimeout = window.setTimeout;
describe('test a method that uses setTimeout', function(){
    var testObject;
    beforeEach(function () {
        // force setTimeout to be called right away, no matter what time they specify
        jasmine.getGlobal().setTimeout = function (funcToCall, millis) {
        testObject = new test();
    afterEach(function() {
        jasmine.getGlobal().setTimeout = realWindowSetTimeout;
    it('should call the method right away', function(){

I got a good pointer from Andreas in this StackOverflow question.

This would also work for window.setInterval.

Other possible approaches:

  • Create a wrapper module of setTimeout and setInterval methods that can be mocked. This can be mocked with RequireJS or passed into the constructor.
  • Pass the window.setTimeout function into the method (this could get messy).


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170624.1 | Last Updated 22 Aug 2014
Article Copyright 2014 by Aligned
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid