Check out our Angular Book Series.

How do I test the rxjs debounceTime() function?

I'm working on an Angular application, and sometimes we use the debounceTime() function. When a user is typing in a text box we may want to trigger a service call based on the characters we type. We use debounceTime() to make sure that user has finished typing for a certain length of time when the service call occurs. Our code might be something like this:

).subscribe( value =>
// do something
this.newValue = value;

The input here is most likely an element in a reactive form.

This says that when the observable is resolved, we wait 300ms before doing something. In that time, if the user types more characters, those characters overwrite the original ones, and we start waiting again. IF there are 300 milliseconds without any more typing, we move forward to the subscribe and do something.

This presented a problem when testing. Here is a sample psuedo test code:

it('should execute some code', () =>
input.setValue('some new value');
expect(newValue).toBe('some new value');

The problem is that the value is set and the expect is checked before we waited 300 milliseconds, and as such the test fails.

The solution is to run the test in a fakeAsync block and make use of the tick() function.

This should fix it:

it('should execute some code', fakeAsync(() =>
input.setValue('some new value');
expect(newValue).toBe('some new value');

The tick() function tells the code to wait, or pause, for 300 milliseconds before proceeding. This is the magic that made the tests like this work.

Warning: I wrote all this code in the browser, so is untested and may have some minor syntax errors; but the approach should be solid.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version