Mocha: How do I test my code which requires 'window' and 'sessionStorage' objects?

Created on 13 May 2016  路  2Comments  路  Source: mochajs/mocha

I am writing an integration test for my application with mocha.
Basically I want to test my authentication flow, which has files making network calls and saving details in browser storage.
I am facing issues with importing a file which requires 'window' and 'sessionStorage' objects. When I run the test file, it gives error where sessionStorage is being used.
ReferenceError: sessionStorage is not defined

I have tried mocking the window and sessionStorage objects in an IIFE using

(function (glob) {
    function mockStorage() {
        var storage = {};
        return {
            setItem: function(key, value) {
                storage[key] = value || '';
            },
            getItem: function(key) {
                return storage[key];
            },
            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;
            }
        };
    }
    glob.localStorage = mockStorage();
    glob.sessionStorage = mockStorage();
}(typeof window !== 'undefined' ? window : global));

before the import calls as well but it still fails.

needs-feedback question

All 2 comments

will need more information than this. how are you running the tests? in what environment? etc.

_note to self: issue template!_

It's been almost a year. Closing due to no response from OP

Was this page helpful?
0 / 5 - 0 ratings

Related issues

helloravi picture helloravi  路  3Comments

eschwartz picture eschwartz  路  3Comments

robertherber picture robertherber  路  3Comments

niftylettuce picture niftylettuce  路  3Comments

wzup picture wzup  路  3Comments