lundi 21 décembre 2015

$httpBackend.flush() causes factory property to be undefined (Karma testing)

Okay this is really stumping me...

I have the following code in my factory (summarized)

angular
    .module('enigma.authFactory', [])    
    .factory('authFactory', authFactory);

authFactory.$inject = ['$http', '$q', '$state', 'sessionStorageFactory'];

function authFactory($http, $q, $state, sessionStorageFactory){
    var auth = {
        login: login,
        isLoggedIn: false,
        hasErrMsg: false
    }

    return auth;

    function login(user){
        return $http.post('login', user)
            .success(function(data){
                auth.isLoggedIn = true;
                if(auth.scope.$close) auth.scope.$close();
            })
            .error(function() {
                auth.hasErrMsg = true;
                auth.errMsg = 'Incorrect password.';
                auth.$dismiss;
            });
    }
}

And then I have the following unit tests

it('should set authFactory.isLoggedIn to true on successful login', function()                 {
    $httpBackend.expectPOST('login').respond(200);
    authFactory.login(user);
    console.log(authFactory.isLoggedIn); // Logs False as expected
    $httpBackend.flush();
    console.log(authFactory.isLoggedIn); // Logs Undefined now and I can't figure out why...
    expect(authFactory.isLoggedIn).toEqual(true);
});

So as the comments say, authFactory.isLoggedIn returns false as expected before $httpBackend.flush() is called but then returns undefined immediately afterwards.

As if that wasn't confusing enough, here's another test that does the exact same thing only it expects authFactory.hasErrMsg to equal true, this test works perfectly.

it('should set hasErrMsg to true if login fails', function () {
    $httpBackend.expectPOST('login').respond(400);
    authFactory.login();
    console.log(authFactory.hasErrMsg); // This logs false as expected
    $httpBackend.flush();
    console.log(authFactory.hasErrMsg); // This logs true as expected
    expect(authFactory.hasErrMsg).toEqual(true);
});

I omitted quite a bit of code here so let me know if you need to see any of the beforeEach() methods.

Does anyone have any ideas why I am seeing this behavior?

Aucun commentaire:

Enregistrer un commentaire