Ilja
Ilja

Reputation: 46527

Check if function returns sessionStorage with jest

I am trying to write a jest test for following function, that sets sessionStorage entry:

/**
 * @desc create authenticated user session
 * @param  {String} [email='']
 * @param  {Date} [expires=Date.now()]
 * @param  {String} [hash='']
 * @param  {Array} users
 * @return {Session}
 */
export const setSession = (
  email = '',
  expires = Date.now(),
  hash = '',
  users: []) => {
  const session = {
    email,
    expires,
    hash,
    users
  };
  sessionStorage.setItem('MY_SESSION', JSON.stringify(session));
};

I am confused to where to start i.e. I get jest error saying that session storage is not defined in a simple test like this:

it('takes in session parameters and returns sessionStorage', () => {
  console.log(setSession('[email protected]', Date.now(), 'ha_sh', []));
});

Upvotes: 1

Views: 1848

Answers (1)

jeremy-denis
jeremy-denis

Reputation: 6878

You will have to mock the session storage in your unit test to be abble to call it.

One way to do this is :

var myStorage = function() {
  var sessionStorage = {};
  return {
    getItem: function(key) {
      return sessionStorage[key];
    },
    setItem: function(key, value) {
      sessionStorage[key] = value.toString();
    },
    clear: function() {
      sessionStorage = {};
    }
  };
};
Object.defineProperty(window, 'sessionStorage', { value: myStorage });

Upvotes: 1

Related Questions