Skip to content

Instantly share code, notes, and snippets.

@jouni-kantola
Created February 2, 2014 02:02
Show Gist options
  • Save jouni-kantola/8761980 to your computer and use it in GitHub Desktop.
Save jouni-kantola/8761980 to your computer and use it in GitHub Desktop.
Sinon.JS used to stub properties and methods in a sandbox. Methods and properties are restored after test(s) are run.
define(['can', 'localCache'], function(can, localCache) {
'use strict';
describe('storeLocal()', function() {
var sandbox;
beforeEach(function() {
// create sandbox environment for mocking about
sandbox = sinon.sandbox.create();
});
afterEach(function() {
// restore the environment as it was before
sandbox.restore();
});
it('should cache in localStorage', function() {
// fake localStorage
var store = {},
localStorageKey,
theOneRing = {
my: 'precious'
},
expected = JSON.stringify(theOneRing);
// stub property for feature detection to use localStorage
sandbox.stub(can.use, 'localStorage', true);
// stub localStorage's setItem and replace with fake
sandbox.stub(window.localStorage, 'setItem', function(key, value) {
store[key] = value;
localStorageKey = key;
});
// call local cache handler
localCache.storeLocal(theOneRing);
// assert
store[localStorageKey].should.equal(expected);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment