简体   繁体   English

如何在Jasmine和Angular中模拟$ http超时

[英]How to simulate $http timeout in Jasmine and Angular

I am trying to simulate http timeout using Jasmine. 我试图使用Jasmine模拟http超时。 I have created an Angular HTTPInterceptor 我创建了一个Angular HTTPInterceptor

angular.module('coreErrorHandler')
.factory('HTTPTimeoutInterceptorService', function($rootScope, $q, AppConfig) {
    return {
        'request': function(config) {
            config.timeout = 2000;
            return config;
        }
    };
});

And I have added the service to $httpProvider 我已将服务添加到$ httpProvider

$httpProvider.interceptors.push('HTTPTimeoutInterceptorService');

The code works 100%, I am just not sure how to test it using Jasmine. 代码工作100%,我只是不知道如何使用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 appreciated. 任何帮助,将不胜感激。 Thanks! 谢谢!

There is no need to use setTimeout here, you have to pass an argument to $timeout.flush() to simulate how long the time has passed. 这里不需要使用setTimeout ,你必须将参数传递给$timeout.flush()来模拟时间已经过去了多长时间。

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 另请参阅: ngMock文档中的$ timeout

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM