2014-03-06 86 views
17

angularJS $httpBackend官方指導我會做這個測試,但噶給我這個錯誤Error: No pending request to flush ! at Function.$httpBackend.flush

測試

'use strict'; 

describe('profileCtrl', function() { 
var scope, $httpBackend; 

beforeEach(angular.mock.module('maap')); 
beforeEach(angular.mock.inject(function($rootScope, $controller, _$httpBackend_){ 

    $httpBackend = _$httpBackend_; 
    $httpBackend.when('GET', 'profile').respond([{id: 1, name: 'Bob'}]); 
    scope = $rootScope.$new(); 
    $controller('profileCtrl', {$scope: scope}); 
})) 

it('should fetch list of users', function(){ 
    $httpBackend.flush(); 
    expectGET(scope.current_user.length).toBe(1); 
    expect(scope.current_user[0].name).toBe('Bob'); 
}); 

});

對於這個簡單控制器

'use strict'; 

angular.module('maap').controller('profileCtrl', function($scope, UserService) { 

$scope.current_user = UserService.details(0); 

});

+0

它是警告還是錯誤? – madhured

+0

@madhured這是一個錯誤 – Tres

回答

27

_$httpBackend_沒有什麼可刷新的,因爲您在測試中沒有發出任何http請求。

您需要調用一些編寫http請求的代碼。

然後,一旦某個地方在您的測試中發出了http請求,您可以調用flush方法,以便爲已完成的請求提供響應。

喜歡的東西:

it('should fetch list of users', function(){ 

    // Do something that will make an http request 
    MyService.getAllUser(function ...) // for example 

    // Then provide a response for the http request that 
    // has been made when getAllUser was called 
    $httpBackend.flush(); 

    // Check the expected result. 
    expect(something).toBe('Bob'); 
}); 
8

同樣的問題發生在我身上,問題是不是,我沒有提出請求,但因爲我正在請求是預期的一個不同:

對於例如,我已經定義了這種預期:

mockBackend.expectGET("http://myapi.com/001").respond("RESULT"); 

而我要求這個其他網址:

http://myapi.com/002 

非常容易混淆的錯誤信息,沒有真正容易與下面的問題相關。

+0

同樣的問題在這裏,但我不能猜到我請求的網址。你怎麼知道?有一種方法可以顯示日誌或東西? – Ruben

+0

感謝您的這一點,我試圖弄清楚爲什麼我的代碼沒有發出http請求,當它顯然應該是。原來,我只是在'expectPOST'網址中輸入了一個錯字。 –

1

我有同樣的問題,因爲我忽略了爲每個預期的請求定義響應。沒有迴應,沒有什麼可以沖洗。另外http承諾永遠不會解決或失敗。

0

我有同樣的異常,因爲我用ngMockE2E模塊,而不是ngMock模塊。即使調用$ rootScope。$ digest()也沒有幫助。