1

I am trying to do a simple HTTP post in my Jasmine test using Karma. I have the code and it works because I use the Chrome app Postman and have successfully retrieved user credentials.

So it must be my unit test. What am I doing wrong?

signInSpec.js:

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

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

    var AuthFactory, httpBackend;

    beforeEach(function($httpBackend, _AuthFactory_) {
        httpBackend = $httpBackend;
        AuthFactory = _AuthFactory_;
    });

    it('should return POST', function(done) {
        AuthFactory.signIn({inputType: {user: "admin"}, credInput: {password: "pass123"}});

    httpBackend.when('POST','http://localhost:3000/api/AuthFactoryServ/signIn')
        .respond (200, {});

    httpBackend.flush(); // to return the response
    }, 20000);

});

and AuthFactory.js:

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

    var AuthFactory = {};

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

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

    return AuthFactory;

}]);

And the error:

PhantomJS 1.9.8 (Windows 7 0.0.0) Service: Authentication should return POST F
AILED
        Error: Timeout - Async callback was not invoked within timeout specifi
ed by jasmine.DEFAULT_TIMEOUT_INTERVAL.
        TypeError: 'undefined' is not an object (evaluating 'AuthFactory.signIn')
            at C:/maink/client/tests/signInSpec.js:1

1 Answer 1

1

You need to mock the actual ajax call so it will call your fake

it('should return POST', function(done) {
     // dont worry about calls to assets
     httpBackend.when ('POST','http://localhost:3000/api/AuthFactoryServ/signIn')
              .respond (200, {});

    AuthFactory.signIn({inputType: {user: "admin"}, credInput: {password: "pass123"}});
    httpBackend.flush(); // to return the response
Sign up to request clarification or add additional context in comments.

7 Comments

don't forget to flush the calls too
@maurycy I added the flush
Cool, now only the AuthFactory.signIn() has to before flush and OP is all set ;)
put the mock before the actual api call.
I updated my code to show the order of mock/api-call
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.