less than 1 minute read

TIL how to mock the internal clock of a test using jasmine. This was useful for testing methods that rely on a timeout or debounce before firing.

I recently wrote a method that is debounced by 500ms. Multiple calls to the method will reset the 500ms timer, and the method will only execute one time after the timer reaches 0.

Jasmine has a nifty feature to test methods that are debounced or use a timeout: by mocking the internal clock of the test file, the tester can advance the clock manually trigger method calls and see how the method responds.

Example:

describe('debounced test', function(){

	beforeEach(function(){
		jasmine.clock().install();
	});

	afterEach(function(){
		jasmine.clock().uninstall();
	});

	it('should call the method only after the 500ms debounce', function(){
		scope.debouncedMethod();

		jasmine.clock().tick(501); //increment clock 501 ms.

		scope.$digest();

		//assertions follow
	});
});

Nifty!

Updated:

Comments