vendredi 1 juillet 2016

sessionStorage is undefined in Jasmine

I followed this post to set my sessionStorage:

but no matter what I did, my sessionStorage is still undefined. I can step into storageMock(), but when I step out, it's still undefined. What did I do wrong?

Here's the code:

/// <reference path="../angular.js" />
/// <reference path="../angular-mocks.js" />
/// <reference path="../angular-animate.js" />
/// <reference path="../angular-ui/ui-bootstrap.js" />
/// <reference path="../angular-ui/ui-bootstrap-tpls.js" />

/// <reference path="../../../bluescopebuildings/app/app.js" />
/// <reference path="../../../bluescopebuildings/app/applicationapp.js" />


describe('Controller: applicationController', function () {
    // Storage Mock
    function storageMock() {
        var storage = {};

        return {
            setItem: function (key, value) {
                storage[key] = value || '';
            },
            getItem: function (key) {
                return storage[key] || null;
            },
            removeItem: function (key) {
                delete storage[key];
            },
            get length() {
                return Object.keys(storage).length;
            },
            key: function (i) {
                var keys = Object.keys(storage);
                return keys[i] || null;
            }
        };
    };
    var applicationCtrl, $scope, $window;


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

        // INJECT! This part is critical
        // $rootScope - injected to create a new $scope instance.
        // $controller - injected to create an instance of our controller.
        // $q - injected so we can create promises for our mocks.
        // _$timeout_ - injected to we can flush unresolved promises.
        inject(function ($rootScope, $controller, $q, _$timeout_,_$window_) {
            $scope = $rootScope.$new();
            $timeout = _$timeout_;
            $window = _$window_;
            $window.sessionStorage = {};
            $window.sessionStorage = storageMock();
            $window.sessionStorage.setItem('userName', 'Thao');
            $window.sessionStorage.setItem('userID', 10);
            $window.sessionStorage.setItem('profileID', 25);

            applicationCtrl = $controller('applicationController', {
                $scope: $scope,
                $window: $window
            });
        });
    });

    it('should return profile', function () {
        //$scope.currentUserID = 10;
        //$scope.currentUserName = 'Thao';
        //$scope.currentJobID = 62;
        //$scope.profile = null;

        $scope.GetProfile();
        expect($scope.profile).not.toBe(null);
    });
});

I tried without calling storageMock(), but it still does not work. Thanks

Aucun commentaire:

Enregistrer un commentaire