red red - 1 year ago 55
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 () {

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)

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



and here is my

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

var AuthFactory = {};

AuthFactory.signIn = function(data) {
return $'', data);

AuthFactory.signOut = function(data) {
return $'', data);

return AuthFactory;


When I run the test, it passes (obviously) but the

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
Jasmine unit test?

Answer Source

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

httpBackend.expect('POST', url + '/api/AuthService/signIn', dataObj)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download