ANTON072
2/2/2014 - 2:02 AM

Sinon.JS used to stub properties and methods in a sandbox. Methods and properties are restored after test(s) are run.

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);
        });
    });
});