Node.js and localStorage

So you’re unit testing your JavaScript using Node, you make calls to and window.localStorage but Node has no equivalent. How do you satisfy the dependency?

I tried using node-localStorage and it worked but as soon as I used webpack to create a bundle I got problems. In my application I make very little use of localStorage so I decided to throw out node-localStorage and create my own implemenation:

var localStorage = {
  _storage: {},

  getItem: function(sKey) {
    if(!sKey || !this._storage[sKey]) return null;
    return this._storage[sKey];

  setItem: function (sKey, sValue) {
    if(!sKey) return;
    this._storage[sKey] = sValue;

  removeItem: function (sKey) {
    if(!sKey) return;
    delete this._storage[sKey];

  clear: function() {
    this._storage = {};

Hardly industrial strength but it only took a few minutes and it gets me through the tests.

Leave a Reply

Your email address will not be published. Required fields are marked *