Testing Input with “debounceTime” using ‘tick()’— Karma-Jasmine Angular Testing

Shashank Vivek
2 min readNov 26, 2020

--

In the world of unit testing in Angular, use of tick() often remains mystery unless we stumble upon its use case. I will try to explain the working of tick() using an Input element.

Photo by Andrea Piacquadio from Pexels

To start with, lets create an HTML element:

and respective component.ts file:

As we can see in this example, the input provided by the user will make a server call. To reduce the repeated call on every input value change (searchValChanged(event) ) , we have put a debounceTime of 1000ms.

Without debounceTime below test case can easily check the behavior of code :

But, now we need to make the angular know that it needs to move ahead with testing only when 1000ms has completed its cycle. To do that , we have tick() to the rescue. The angular docs have explained tick in brief as:

Simulates the asynchronous passage of time for the timers in the fakeAsync zone.

This clearly matches our requirement.

Note: "tick()” can only be used within “fakeAsync" block

fakeAsync gives us control over time when working with tick() .

To sum it up, the final test file would look something like :

You can find the complete code on my github repository .

If you like this article, please 👏 clap 👏 few times & encourage me 🐼 to write more.

--

--