red red - 4 months ago 12
AngularJS Question

Testing a service function POST response with Jasmine

I'm not entirely sure how to do this but I have a endpoint URL which is a POST request for login authentication. When you add a request payload, you will get either a successful login credential or an error. However, I seem to have problems with fetching the response.

Here is my spec file:

describe('Service: AuthFactory',function(){

beforeEach(function () {
module('ui.router');
module('users');
module('main');
});

var AuthFactory, httpBackend;

beforeEach(inject(function($httpBackend, $rootScope, $controller, _AuthFactory_){
httpBackend = $httpBackend;
AuthFactory = _AuthFactory_;

}));

it('Return a POST response from a Service function', function() {
var url = "http://localhost:3000";
var dataObj = JSON.stringify({
inputUser: { user: "TestCase1" },
inputPass: { password: "TestPass1" }
});
httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
.respond({});

AuthFactory.signIn(dataObj).success(function(response) {
console.log(response);
// outputs Object {}
// when in reality it should
// output the response to POST
// eg: { "login": { "user": "Test_User", "time": 54935934593 }, "outputHead": { "token": asjfjj234kfAd } }
});

httpBackend.flush();

expect(true).toBe(true);
});
});


and here is my
Service
.

angular.module('users').factory('AuthFactory', ['$http', function($http) {

var AuthFactory = {};

AuthFactory.signIn = function(data) {
return $http.post('http://127.0.0.1:3000/api/AuthService/signIn', data);
};

AuthFactory.signOut = function(data) {
return $http.post('http://127.0.0.1:3000/api/AuthService/signOut', data);
};

return AuthFactory;

}]);


When I run the test, it passes (obviously) but the
console.log()
outputs
Object{}
.

And when I use a Chrome extension like Postman. I do an example POST request and the response that returns is the login credentials! So why is it working on Postman but not on my
AngularJS
Jasmine unit test?

Answer

This line is why you get an empty object as your response:

httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
        .respond({});

To give the response you want just add the following:

httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)
            .respond({"login": { "user": "Test_User", "time": 54935934593 }, "outputHead": { "token": asjfjj234kfAd }});

See the documentation for more information.

Comments