2016-12-06 30 views
1

我有一個服務,而該服務裏面,我有像這樣

settings.updateProfile = function(patient){ 
     return $q(function(resolve, reject) { 
      var user = patient; 
       dbService.updateUser(user).then(
        function (response) { 
         if (response.res) { 
          LoopBackAuth.setUser(LoopBackAuth.accessTokenId, response.res.name, LoopBackAuth.currentUserRole); 
          LoopBackAuth.save(); 
          location.reload(); 
          patient.name == response.res.name ? resolve(true) : resolve(false); 
         } 
        }, 
        function (error) { 
         resolve(false); 
        } 
       ); 

     }); 
    }; 

這裏dbService.updateUser功能功能包含$承諾以及服務功能。我想測試這個函數,並檢查它是否解析爲真或假。我知道http api調用我們使用$ httpBackend服務。但它並不像我期待的那樣工作。現在我正在像這樣測試它。

it('Should return correct result', function() { 
     var result = true; 
     var patient = {"name": "newUser"}; 

     $httpBackend.whenGET(patient).respond(200, $q.when(result)); 
     expect(settingsFactory.updateProfile).not.toHaveBeenCalled(); 
     expect(result).toEqual(true); 

     settingsFactory.updateProfile(patient) 
      .then(function(res) { 
       result = res; 
      }); 

     $httpBackend.flush(); 
     expect(settingsFactory.updateProfile).toHaveBeenCalledWith(patient); 
    }); 

它表示錯誤:

Error: Unexpected request 
+1

您沒有正確測試,您應該先設置$ httpBackend以在請求端點時響應200。然後打電話給你的服務,並等待承諾測試 – MayK

+0

我沒有完全讓你。你可以請改變我的測試並用代碼顯示它嗎?謝謝 –

+1

只是關於你的代碼結構的註釋:如果'dbService.updateUser(user)'返回一個promise,你根本不需要使用'$ q',只需返回整個'dbService.updateUser(...)。然後(...)'表達式並從處理函數中返回'true'或'false'。 – Duncan

回答

1
$httpBackend.whenGET(patient).respond(...); 

失敗因爲patient是一個對象{"name": "newUser"}和whenGET期待一個字符串。例如:

$httpBackend.whenGET('/patient').respond(...);