how does timeout work in angular tests running in karma
In your unit tests, you load ngMock
, which overwrites the orignal $timeout
with its mock. Mock $timeout
doesn't work like the real JavaScript timeout
. To get it to call the code that's inside it, you have to do $timeout.flush()
from your unit test.
If $timeout
worked like the real timeout
, you would've had to write asynchronous unit-tests for all functions that use $timeout
.
Here's an example of a simplified function that uses $timeout
and how I test it:
gaApi.getReport = function() { report = $q.defer() $timeout(function() { $http({method: 'GET', url: 'https://www.googleapis.com/analytics/v3/data/ga'}) .success(function(body) { report.resolve(body) }) }, 300) return report.promise}
A unit test:
describe('getReport', function() { it('should return report data from Google Analytics', function() { gaApi.getReport().then(function(body) { expect(body.kind).toBe('analytics#gaData') }) $timeout.flush() $httpBackend.flush() })})