$ http超时测试jasmine angular

时间:2015-06-30 14:42:23

标签: angularjs jasmine

我正在尝试测试我的模块APICompare

var APIClient = function($http) {
    this.send = function(data) {
        $http({
            method: data.method,
            url: data.url,
            headers: data.headers,
            data: data.data
        }).success(function(response, status){
            data.success(response, status);
        }).error(function(response, status){
            data.error(response, status);
        });
    }
}

angular.module('api.client', []).factory('APIClient', ['$http' function($http)
{
    var client = new APIClient($http);

    return {
        send: function(data)
        {
            return client.send(data);
        },
    }

}]);

和测试

describe('send', function() {

    var apiClient, $httpBackend;

    beforeEach(module('compare'));

    beforeEach(inject(function($injector) {
        $httpBackend = $injector.get('$httpBackend');
        apiClient = $injector.get('APIClient');
    }));

    it ('Should check if send() exists', function() {
        expect(apiClient.send).toBeDefined();
    });

    it ('Should send GET request', function(done) {
        var url = '/';

        $httpBackend.when('GET', url).respond({});

        apiClient.send({
            method: 'GET'
            url: url,
            data: {},
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
            success: function(data, status) {
                console.log(status);
                done();
            },
            error: function(data, status) {
                console.log(status);
                done();
            }
        });
    });
});

但每次我都有

PhantomJS 1.9.8 (Mac OS X) send Should send GET request FAILED
    Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Ti似乎忽略了$httpBackend.when('GET', url).respond({});,但我不知道为什么。

1 个答案:

答案 0 :(得分:2)

您需要致电$httpBackend.flush

您应该在http请求完成后执行此操作 - 很可能在您的断言之前。这也会同步请求,并且无需successerror回调。

另请注意,如果出现错误,您可能希望使用错误调用done,以便测试失败 - 除非您想要