I'm working with a team that is upgrading to a modern Angular version that no longer uses the zone.js library. This upgrade help makes angular work more effectively, but is beyond the scope of this article.
In our test suite, we had some tests like this:
The ticks were, primarily, in the code because we were using a timer, and the tick() method was an easy way to increment the timer.
The fakeAsync() block code did not work in the context of a zoneless application. There are some instructions out there for setting up zone.js just for application testing, however I decided to dig a bit deeper and look for a different solution.
I found the answer in the jasmine.clock()
First, in my tests I had to set it up:
2jasmine.clock().install();
Why did I have to uninstall it, then install it? Because of some weird bug, which I hope will be fixed and no longer be a future issue.
The next step is to initialize the clock with a mockDate():
Now, in our test, we can use the jasmine.clock().tick():
And the code started working.
At the end of the test, I have been uninstalling the clock:
A full, psuedocode sample test, so you can see all the lines in context:
2 // set up Jasmine clock
3 jasmine.clock().uninstall();
4 jasmine.clock().install();
5 jasmine.clock().mockDate(new Date(2025, 0, 1));
6
7 // do something
8 jasmine.clock().tick(1000);
9 // check stuff
10
11 // remove Jasmine clock
12 jasmine.clock().uninstall();
13}));
My code started working wonderfully. I have a video cast series about the various ways to test asnyc code with Angular, maybe I should add another to cover this. What do you think?
