Recently I wrote some code that contained a setTimeout. The reason was so that the UI could catch up before the function actually fired – something that I’ve found the need to do with javascript from time to time.
So, when it comes to testing the code… my test just skipped along until it literally skipped the block inside of the setTimeout. I tried a bunch of different things to get it to slow down, but this is the one that worked.
jasmine.clock
jasmine.clock will effectively allow you to time travel. You can jump forward in time, running any code that would run during that time. For our case, it makes it so the code within the setTimeout block can run, but it also has the benefit of speeding up your test run (for example, if you need to wait 10 seconds, you can just fast forward 10 seconds without actually waiting 10 seconds…. no one likes a slow test, after all!).
Setup
In order to use jasmine.clock, you need to install it before you use it.
Installation effectively overwrites the built-in functions (setTimeout, setInterval, etc), and allows jasmine to keep track of the state of all the operations for easier testing.
If you’re testing a bunch of test cases over the same block of code, you can easily just put this in to a beforeEach:
Cleanup
After each test, you’ll also want to uninstall the clock, setting the implementations of setTimeout, setInterval, etc back to normal.
Again, if you’re testing a bunch of test cases over the same block of code, you can use an afterEach:
Usage
To use the clock, simply call .tick(x), where x is the number of milliseconds you want to time travel: