AngularJS: how to check factories

I have a session.factory.jsfactory:

(function() {
    'use strict';

    angular
        .module('app')
        .factory('Session', Session);

    function Session() {
        var sessionId;

        return {
            create: create,
            destroy: destroy,
            isAuthenticated: isAuthenticated
        };

        function create(id) {
            sessionId = id
        }

        function destroy() {
            sessionId = null;
        }

        function isAuthenticated() {
            return !!sessionId;
        }
    }
})();

And I want to check it out, so I did session.factory.spec.js:

describe('Session', function() {
    var Session;

    beforeEach(function(){
        module('app');

        inject(function(_Session_){
            Session = _Session_;
        });
    });
});

But Sessionfor some reason undefined. What am I missing?

+4
source share
1 answer

You just need to load it into your module as follows:

describe('Session', function() {
    var Session;

    beforeEach(module('app'));  //added

    beforeEach(inject(function(_Session_){
            Session = _Session_;
    });
});

module('app')returns a function, which is then called before each. The way you use it in the OP, the function created is never called.

inject- same. It should be directly inside beforeEach.

EDIT:

The above code - the usual way of doing this, but it turns out that you can also define the functions moduleand injecthow to work OP.

plunker , , . , .

:

angular
        .module('app')
        .factory('Session', Session);

:

angular
        .module('app', [])
        .factory('Session', Session);

[] , , ( ). .

+3

Source: https://habr.com/ru/post/1589249/


All Articles