Zen Zen - 4 months ago 16
AngularJS Question

How to get the params from an http requests when unit testing in angularjs?

I have defined a method for my controller, like

$scope.submitForm = ( username, password ) =>{
$http({
method: 'post',
url: 'balabala',
params: {username, password}
}).success( res => { /* */ } );
}


My test specs look like:

descript('myController', () => {
beforeEach(module('myModule'));

let controller, httpBackend, http, scope;

beforeEach(inject(($controller, $httpBackend, $http, $scope) => {
scope = $scope.$new();
httpBackend = $httpBackend;
http = $http;
controller = $controller;

httpBackend.when('POST', '/login')
.respon({
result: 'ok'
});
}));

it('should POST login', () => {
httpBackend.expectPOST('/login');
const myController = controller('myController', {
$scope: scope,
$http: http
});
scope.submitForm();
httpBackend.flush();
});
});


How can I make sure that
username
and
password
have been posted?

Answer

Add a response value associated to post i.e

httpBackend.expectPOST('/login').respond({success:true});

And don't use when because expectPost will make sure that you are calling that post method if not it will throw an error if you are getting no errors then assume that post method has been called.

$httpBackend .whenGET('/testpath/testurl/z/values?max=10&min=1').respond(function(method, url, data, headers, params) {

// params will be {
//   max: 10,
//   min: 1
// }

});