dimanche 18 septembre 2016

cant update jasmine spy

Hi I have a Angular service that uses another service that loads data from the local storage on init.

angular
    .module('app')
    .factory('localStorage', function ($window)
    {
        if (!$window.localStorage)
        {
            // throw Error
        }

        return $window.localStorage;
    });

angular
    .module('app')
    .factory('session', function (localStorage)
    {
        var container = JSON.parse(localStorage.getItem('sessionContainer'));

        return {
            getUser: getUser
        };
    });

Now i want to test the session service.

    describe('SessionService', function ()
    {
        var service;
        var localStorageMock;

         // Load the module.
        beforeEach(module('appRegistration'));

        // Create mocks.
        beforeEach(function ()
        {
            logMock = {};

            localStorageMock = jasmine.createSpyObj('localStorageServiceMockSpy', ['setItem', 'getItem']);
            localStorageMock.getItem.and.returnValue('{}');

            module(function ($provide)
            {
                $provide.value('localStorage', localStorageMock);
            });

            inject(function (_session_)
            {
                service = _session_;
            });
        });

        it('should call `getItem` on the `localStorageService` service', function ()
        {
            expect(localStorageMock.getItem).toHaveBeenCalledWith('sessionContainer');
        });

        describe('getUser method', function ()
        {
            it('should return an empty object when the user is not set', function ()
            {
                var result = service.getUser();

                expect(result).toEqual({});
            });

            it('should return the user data', function ()
            {
                // localStorageMock.getItem.and.returnValue('{"user":{"some":"data"}}');

                var result = service.getUser();

                expect(result).toEqual({some: 'user data'});
            });
        });

    });

As you can see in the should return the user data section. I need a way to update the container so getUser returns the expected data.

I tried to update the getItem spy, but this does not work. The localStorageMock is already injected in the session service when i want to change the spy.

Any help?

Aucun commentaire:

Enregistrer un commentaire