2015-06-30 40 views
1

我想測試我的模塊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. 

鈦看來$httpBackend.when('GET', url).respond({});被忽略但我不知道爲什麼。

回答

2

您需要致電$httpBackend.flush。你的斷言之前最有可能正確的 -

你應該這樣做的http請求已經作出。這也同步了請求,並消除了對回調的需求successerror

另請注意,如果出現錯誤,您可能希望打電話給done,以使您的測試失敗 - 除非您的想要