2016-04-27 64 views
1

我有一個service factory連接並與api交互的數據。下面是該服務:服務承諾不解決與業力

angular.module('dbRequest', []) 
    .factory('Request', ['$http', 'localConfig', function($http, localConfig){ 
    return { 
     getDataRevision: function(){ 
     return $http({ 
      url: localConfig.dbDataUrl, 
      method: "GET", 
      crossDomain: true, 
      headers: { 
      'Content-Type': 'application/json; charset=utf-8' 
      } 
     }) 
     } 
    } 
    }]); 

this answer以線索,這是我正在測試方法:

describe('Service: Request', function() { 
    var $scope, srvMock, $q, lc, $httpBackend; 

    beforeEach(module('webApp')); 

    beforeEach(inject(function($rootScope, Request, _$q_, _$httpBackend_, localConfig){ 
    $scope = $rootScope.$new(); 
    srvMock = Request; 
    $q = _$q_; 
    $httpBackend = _$httpBackend_; 
    lc = localConfig; 

    $httpBackend.expect('GET', lc.dbDataUrl); 

    $httpBackend.when('GET', lc.dbDataUrl).respond({ 
     success: ["d1","d2", "d3"] 
    }); 
    })); 

    it('should return a promise', function(){ 
    expect(srvMock.getDataRevision().then).toBeDefined(); 
    }); 

    it('should resolve with data', function(){ 
    var data; 
    var deferred = $q.defer(); 
    var promise = deferred.promise; 

    promise.then(function(res){ 
     data = res.success; 
    }); 

    srvMock.getDataRevision().then(function(res){ 
     deferred.resolve(res); 
    }); 

    $scope.$digest(); 

    expect(data).toEqual(["d1","d2", "d3"]); 
    }) 
}); 

should return a promise傳球,但未來should resolve with data失敗,此錯誤:

Expected undefined to equal [ 'd1', 'd2', 'd3' ]. 

但是,service方法getDataRevision被調用,但沒有通過模擬諾言得到解決我在測試中。我如何進行修正?

回答

1

目前您所期待嘲笑的數據在那裏在data變量沒有沖洗httpRequest S,但是這不會發生,直到你flush所有httpRequest秒。 $httpBackend.flush()所做的是,它將模擬數據返回給您使用$httpBackend.when('GET', lc.dbDataUrl).respond所做的特定請求。

此外,你不需要額外的承諾,這將是一個開銷。而不是有定製的承諾,你可以利用服務功能返回承諾本身就像下面。

代碼

it('should resolve with data', function(){ 
    var data; 

    srvMock.getDataRevision().then(function(res){ 
     data = res.success; 
    }); 

    $scope.$digest(); 
    $httpBackend.flush(); //making sure mocked response has been return 
    //after .then evaluation only below code will get called. 
    expect(data).toEqual(["d1","d2", "d3"]); 
}) 
+0

解決方案完美的作品!但是,你介意解釋測試用例是如何執行的嗎?由於'httpbackend成功'響應總是等於'預期數據'?換句話說,如何(我/我應該)測試從服務'promise'返回的'response'? – faizanjehangir

+0

@faizanjehangir我做到了..做看看更新.. –