-
-
Save akolybelnikov/3bbfaac3e38a4538bf92a4ee18aece15 to your computer and use it in GitHub Desktop.
Mock localStorage for jasmine tests in TypeScript. This is the testing script. Copy the parts between snip and snap to mock your localStorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="../../library.test.d.ts"/> | |
import * as angular from "angular"; angular; | |
import * as mocks from "angular-mocks/ngMock"; mocks; | |
describe('feat(localStorage Mock): ', function() { | |
beforeAll(() => { | |
angular.module('mock-module',[]) | |
}); | |
// --- snip --- | |
// Mock localStorage | |
beforeEach(() => { | |
var store = {}; | |
spyOn(localStorage, 'getItem').and.callFake( (key:string):String => { | |
return store[key] || null; | |
}); | |
spyOn(localStorage, 'removeItem').and.callFake((key:string):void => { | |
delete store[key]; | |
}); | |
spyOn(localStorage, 'setItem').and.callFake((key:string, value:string):string => { | |
return store[key] = <string>value; | |
}); | |
spyOn(localStorage, 'clear').and.callFake(() => { | |
store = {}; | |
}); | |
}); | |
// --- snap --- | |
beforeEach(()=> { | |
angular.mock.module('mock-module'); | |
}); | |
it('should set an Item', () => { | |
expect(localStorage.setItem('foo', 'bar')).toBe('bar'); // bar | |
expect(localStorage.getItem('foo')).toBe('bar'); // bar | |
}); | |
it('should return null for non existing items', () => { | |
expect(localStorage.getItem('foo')).toBeNull(); // null | |
}); | |
it('should set and remove Item', () => { | |
expect(localStorage.setItem('foo', 'bar')).toBe('bar'); // bar | |
expect(localStorage.removeItem('foo')).toBeUndefined(); // undefined | |
expect(localStorage.getItem('foo')).toBeNull(); // null | |
}); | |
it('should clear the storage', () => { | |
expect(localStorage.setItem('foo', 'bar')).toBe('bar'); // bar | |
expect(localStorage.setItem('bar', 'foo')).toBe('foo'); // foo | |
expect(localStorage.clear()).toBeUndefined(); // undefined | |
expect(localStorage.getItem('foo')).toBeNull(); // null | |
expect(localStorage.getItem('bar')).toBeNull(); // null | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment