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.
(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');
}
}
})();
A simple test I'm trying to do is just stub out the sessionStorage and inject my stub for my test.
'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');
});
});
});
Enter data in either box and click the button to store it. If you navigate to this page in a new window or tab, or quit and relaunch your browser, localStorage will remain and sessionStorage will disappear. Then try clearing your cache and reloading the page.
Karma handles the process of creating HTML files, opening browsers and running tests and returning the results of those tests to the command line. If you use the Angular CLI to manage projects it automatically creates stub Jasmine spec files for you when generating code.
Jasmine is a behavior driven development framework for JavaScript that has become the most popular choice for testing AngularJS applications. Jasmine provides functions to help with structuring your tests and also making assertions.
You can simply create an normal object to achieve what you need, like this:
describe("session", function() {
...
beforeEach(inject(function (_session_, _$window_) {
session = _session_;
$window = _$window_;
$window.sessionStorage = { // mocking sessionStorage
getItem: function(key) {
return this[key];
}
};
}));
...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With