如何使用Jasmine和Karma模拟angularjs $ window.sessionStorage

时间:2014-04-30 14:47:04

标签: angularjs unit-testing jasmine stub

我是Jasmine的新手,在使用Jasmine测试angularjs SPA时试图弄清楚如何模拟$ window.sessionStorage对象。

(function() {                            
    'use strict';                        

    var serviceId = 'session';                                                  

    // Define the service on the module. 
    // Inject the dependencies.          
    // Point to the service definition function.
    angular.module('app').service(serviceId, ['$window', session]);

    function session($window) {                                                 

        var token = null;                                                       

        var service = {                  
            create: create,              
            destroy: destroy,            
            getToken: getToken,          
            read: read                   
        };                               

        return service;                  

        ...

        /**
         * Get the session token
         */
        function getToken() {
            return this.token;
        }

        /**                              
         * Read session variables from local session storage
         */                                                                     
        function read() {                
            this.token = $window.sessionStorage.getItem('token');
        }                                                                       
    }                                                                           
})(); 

我正在尝试的一个简单测试就是将sessionStorage存根并为我的测试注入我的存根。

'use strict';

describe("session", function() {
    var session;
    var $window;
    beforeEach(module("app"));
/*
    beforeEach(function() {
        $window = {sessionStorage: {replace: jasmine.createSpy()}};

        module(function($provide) {
            $provide.value('$window', $window);
        });
    });
*/
    beforeEach(inject(function (_session_) {
        session = _session_;
    }));

    describe("read", function() {
        it("should read session data from the window", function() {
            $window.sessionStorage.token = 'token';        
            session.read();                        

            expect(session.getToken()).toBe('token');
        });                                          
    });
});

1 个答案:

答案 0 :(得分:11)

您可以简单地创建一个普通对象来实现您的需求,例如:

describe("session", function() {

    ...

    beforeEach(inject(function (_session_, _$window_) {
        session = _session_;
        $window = _$window_;

        $window.sessionStorage = { // mocking sessionStorage
            getItem: function(key) {
                return this[key];
            }
        };
    }));

    ...
});