Reputation: 2441
Trying to cover http requests of my app by unit tests. I use Jasmine and Karma and step by step write my code using this tutorial: https://docs.angularjs.org/api/ngMock/service/$httpBackend. But I get an error:
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)
This answer Unit testing AngularJS controller with $httpBackend is so popular for my problem but when I move const controller = createController();
down - I've got another one error: Error: Unsatisfied requests: POST http://loalhost:5000/register
.
Where is my mistake? What I implemented wrong?
My unit test:
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();
});
Block of code from the controller:
$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
I also tried to add before each $httpBackend.flush()
this one (like here Angularjs testing (Jasmine) - $http returning 'No pending request to flush'):
if(!$rootScope.$$phase) {
$rootScope.$apply();
}
But anyway, nothing change.
Upvotes: 0
Views: 556
Reputation: 5432
You call $httpBackend.flush() after controller creation here:
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();
});
Should be like this:
it('should successfully register user', () => {
const controller = createController();
$httpBackend.expectPOST('http://loalhost:5000/register').respond();
$scope.next('[email protected]', '123456');
$httpBackend.flush();
});
Upvotes: 1