2017-03-14 40 views
0

我有和我想測試的角度服務。在他的一個方法中,我使用角度服務的$ http。我只是想嘲笑該功能(更具體的模擬$ http.post函數),將返回任何我想要的,並將此模擬注入我的服務測試。

我試圖找到解決方案,我發現$ httpBackend但我不確定這可以幫助我。

爲MyService看起來像這樣:

angular.module('app').service('MyService' , function (dependencies) { 
    let service = this; 
    service.methodToTest = function() { 
     $http.post('url').then(function() { 
      // Do something 
     }); 
    } 
} 
  • 我想測試methodToTest和注入的$ http.post()模擬

PS請記住,$ http.post( )回覆承諾,所以我認爲我需要考慮這一點。

+0

你可能想編輯你的問題標題,說你需要幫助嘲弄'$ http.post',這似乎是主要問題 – Matthias

+0

@Matthias謝謝。 – Sagie

回答

1

這聽起來像是$httpBackend的用途。

你也可能只能夠$http.post通過執行類似$http.post = jasmine.createSpy();如果您在您的測試注入$http嘲笑,但我不知道。

如果你使用$httpBackend,也許這個例子可以幫助你,在你茉莉測試做這樣的事情

beforeEach(inject(function(_$httpBackend_){ 
    // The injector unwraps the underscores (_) from around the parameter names when matching 
    $httpBackend = _$httpBackend_; 

    $httpBackend.whenRoute('POST', 'url') 
    .respond(function(method, url, data, headers, params) { 

     expect(somevariable).toContain(params.something); 

     return [200, '{"progress":601}']; 
    }); 
})); 

$httpBackend會攔截所有$http.post「s到url並執行此功能。它應該像methodToTest提交給實際url並得到你的假返回值。

返回值表示成功http狀態碼(200),並返回您在第二個參數中放置的任何內容作爲響應的data屬性(此處爲response.data == '{"progress":601}')。這將在then函數中。請參見How do I mock $http in AngularJS service Jasmine test?

expect函數只是一個示例(不需要),向您展示如果需要,您可以將expect子句放在那裏。

+0

只是爲了確定。期望函數在這個方法中做了什麼? (這個聲明的目的是什麼?)。這個''返回[200,'{「progress」:601}'];'是什麼會被返回到'then'函數? – Sagie

+0

我通過更新我的答案回答了您的問題。 – Matthias

1

P.S請記住$http.post()返回承諾,所以我認爲我需要考慮。

的服務需要返回承諾:

angular.module('app').service('MyService' , function (dependencies) { 
    let service = this; 
    service.methodToTest = function() { 
     //$http.post('url').then(function() { 
     //vvvv RETURN http promise 
     return $http.post('url').then(function() { 
      // Do something 
     }); 
    } 
} 

當一個功能省略了return聲明,它的回報undefined值。服務無法向用戶指示成功或失敗。

相關問題