Testing Time Dependent Code with Jasmine Clock

Brittany Hartmire
Code Journal
Published in
2 min readAug 2, 2019

During my time preparing for the Code Chrysalis Immersive, I needed to write my own specs and implementation for various Lodash methods. I’ll be talking about my solution for _.throttle(func, [wait=0]]).

This method takes two parameters, a callback function and a number which represents milliseconds. When a function gets passed into the _.throttle method, it can only be invoked every x milliseconds. In other words, if you pass in a callback function and the number 5000 to _.throttle, you must wait at least 5000 milliseconds in between the callback function’s invocations. Here is my solution:

This code utilizes closures. If you’re unfamiliar with JavaScript closures, I’ve previously published a post about that as well.

I’m adding a custom inThrottle property to my execute variable, which is assigned to a function that gets returned in a closure. This inThrottle property will return a boolean, which will be true during the wait period and false when the wait period is over. When inThrottle is false, func is free to be invoked again. When it gets invoked again, inThrottle will be reassigned to true again, and the cycle continues…

Now how to write a spec that can test whether this function is working correctly?

I wrote my specs using Jasmine. After researching a bit about how to test time dependent code in JavaScript, I learned that Jasmine actually has a built-in mock clock.

To use this mock clock, you simple install it with jasmine.clock().install(). You can tick your clock forward by a specified number of milliseconds with the tick() method and uninstall it with uninstall(). Easy, right? I was so pleased to learn about this feature. Here’s my throttle test:

--

--