title: How to mock angularjs $window.sessionStorage with Jasmine and Karma
body: <p>I'm brand new to Jasmine and trying to figure out how to mock the $window.sessionStorage object when testing an angularjs SPA using Jasmine.</p>
  
  <pre><code>(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');
          }                                                                       
      }                                                                           
  })(); 
  </code></pre>
  
  <p>A simple test I'm trying to do is just stub out the sessionStorage and inject my stub for my test.</p>
  
  <pre><code>'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');
          });                                          
      });
  });
  </code></pre>