How to simulate $ http timeout in Jasmine and Angular
I am trying to simulate http timeout using Jasmine. I created Angular HTTPInterceptor
angular.module('coreErrorHandler')
.factory('HTTPTimeoutInterceptorService', function($rootScope, $q, AppConfig) {
return {
'request': function(config) {
config.timeout = 2000;
return config;
}
};
});
And I added the service to $ httpProvider
$httpProvider.interceptors.push('HTTPTimeoutInterceptorService');
The code works 100%, I'm just not sure how to test it with Jasmine.
it('should wait for the timeout to elapse and issue an HTTP timeout error', function() {
$httpBackend.when("GET", "http://google.com").respond({});
var httpGetValue = $http.get("http://google.com");
setTimeout(function(){
$timeout.flush();
console.log(httpGetValue);
expect(SOMETHING).toEqual(false);
}, 2100);
});
Any help would be greatly appreciated. Thank!
+3
source to share
1 answer
There is no need to use here setTimeout
, you need to pass an argument $timeout.flush()
to simulate how much time has passed.
it('should wait for the timeout to elapse and issue an HTTP timeout error', function() {
$httpBackend.when("GET", "http://google.com").respond({});
var httpGetValue = $http.get("http://google.com");
$timeout.flush(2100); // specify how long to simulate here
console.log(httpGetValue);
expect(SOMETHING).toEqual(false);
});
Also see: $ timeout in ngMock documentation
Hope it helps.
+2
source to share