$http超时测试jasmine angular



我正在尝试测试我的模块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({});,但我不知道为什么。

您需要调用$httpBackend.flush

您应该在发出http请求时执行此操作——很可能就在断言之前。这也同步了请求并消除了对successerror回调的需要。

还要注意,如果出现错误,您可能希望调用带有错误的done,这样您的测试就会失败——除非您想要

最新更新