samedi 28 mars 2015

How do I unit test localStorage being undefined with Mocha/Sinon/Chai

I have 2 simple methods that abstract reading and writing to localStorage:



_readLocalStorage: function(key) {
if (window.localStorage && window.localStorage.getItem(key)) {
return JSON.parse(window.localStorage.getItem(key));
} else {
throw new Error('Could not read from localStorage');
}
},

_writeLocalStorage: function(key, data) {
try {
window.localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
throw new Error('Could not write to localStorage');
}
},


Obviously, stubbing window.localStorage.getItem/setItem is simple. But what about the case where localStorage is undefined?


I've tried caching/unhinging window.localStorage (the second assertion):



describe('#_readLocalStorage', function() {
it('should read from localStorage', function() {
// set up
var stub1 = sinon.stub(window.localStorage, 'getItem')
.returns('{"foo": "bar"}');

// run unit
var result = service._readLocalStorage('foo');

// verify expectations
expect(result)
.to.eql({foo: 'bar'});

// tear down
stub1.restore();
});

it('should throw an error if localStorage is undefined', function() {
// set up
var cachedLocalStorage = window.localStorage;
window.localStorage = undefined;

// run unit/verify expectations
expect(service._readLocalStorage('foo'))
.to.throw(new Error('Could not write to localStorage'));

// tear down
window.localStorage = cachedLocalStorage;
});
});


This does not work however. Mocha/Chai seem not to catch the thrown error.


I've looked around a bit but can't find any way to handle this.


Aucun commentaire:

Enregistrer un commentaire