2017-06-17 96 views
0

嘗試通過單元測試覆蓋我的應用的http請求。我使用Jasmine和Karma,並一步一步地使用本教程編寫我的代碼:https://docs.angularjs.org/api/ngMock/service/ $ httpBackend。但是,我得到一個錯誤:

Error: No pending request to flush ! 
     at Function.$httpBackend.flush (eval at <anonymous> (app/index.js:105:1), <anonymous>:1839:41) 
     at Object.eval (eval at <anonymous> (app/index.js:137:1), <anonymous>:37:20) 

這個答案Unit testing AngularJS controller with $httpBackend是我的問題很普遍,但是當我移動const controller = createController();下來 - 我有另外一個錯誤:Error: Unsatisfied requests: POST http://loalhost:5000/register

我的錯誤在哪裏?我執行錯了什麼?

我的單元測試:

$scope.status; 
    $scope.isFetching = false; 

    const handleResponse = response => { 
    $scope.status = response.status; 
    $scope.isFetching = false; 
    }; 

    $scope.next = (email, password) => { 
    $scope.isFetching = true; 
    $http 
     .post('http://localhost:5000/register', { email, password }) 
     .then(response => handleResponse(response)) 
     .catch(response => handleResponse(response)); 
    }; 

UPD

我也嘗試過每一個$httpBackend.flush()之前添加這一個(喜歡這裏Angularjs testing (Jasmine) - $http returning 'No pending request to flush'

beforeEach(window.module(ngModule.name)); 

let $httpBackend, $rootScope, $controller, $scope, createController; 

beforeEach(
    inject($injector => { 
    $httpBackend = $injector.get('$httpBackend'); 
    $controller = $injector.get('$controller'); 
    $rootScope = $injector.get('$rootScope'); 
    $scope = $rootScope.$new(); 

    createController =() => 
     $controller('RegistrationController', { $scope }); 
    }) 
); 

afterEach(() => { 
    $httpBackend.verifyNoOutstandingExpectation(); 
    $httpBackend.verifyNoOutstandingRequest(); 
}); 

it('should successfully register user',() => { 
    const controller = createController(); 
    $httpBackend.flush(); 
    $httpBackend.expectPOST('http://localhost:5000/register').respond(); 
    $scope.next('[email protected]', '123456'); 
    $httpBackend.flush(); 
}); 

從控制器的代碼塊):

if(!$rootScope.$$phase) { 
    $rootScope.$apply(); 
} 

但無論如何,沒有什麼改變。

回答

1

您控制器創建這裏後調用$ httpBackend.flush():

it('should successfully register user',() => { 
    const controller = createController(); 
    $httpBackend.flush(); //<-- this is not necessary if controller creation doesn't involve $http calls 
    $httpBackend.expectPOST('http://loalhost:5000/register').respond(); 
    $scope.next('[email protected]', '123456'); 
    $httpBackend.flush(); 
}); 

應該是這樣的:

it('should successfully register user',() => { 
    const controller = createController(); 
    $httpBackend.expectPOST('http://loalhost:5000/register').respond(); 
    $scope.next('[email protected]', '123456'); 
    $httpBackend.flush(); 
}); 
+0

哦,我的上帝。我花了大約2個小時來解決這個問題。非常感謝! – rel1x

+0

@ rel1x非常歡迎:) –