Mock the window.setTimeout in a Jasmine test to avoid waiting

, 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{ window.setTimeout(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) { funcToCall; }; testObject = new test; }); afterEach(function { jasmine.getGlobal.setTimeout = realWindowSetTimeout; }); it('should call the method right away', function{ testObject.testWithTimeout; expect(testObject.timeoutWasCalled).toBeTruthy; }); });

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 is part of the GWB Archives. Original Author: Aligned

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.