UNPKG

@empathyco/x-storage-service

Version:
76 lines 3.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var browser_storage_service_1 = require("../browser-storage-service"); var storage; var prefix = 'custom'; var key = 'key'; var anotherKey = 'another-key'; var item = { a: 'item', b: true, c: 288 }; var startingTimestamp = 1563868724320; describe('testing BrowserStorageService', function () { beforeEach(function () { localStorage.clear(); storage = new browser_storage_service_1.BrowserStorageService(localStorage); Date.now = jest.fn(function () { return startingTimestamp; }); }); it('saves an item in local storage', function () { storage.setItem(key, item); expect(localStorage).toHaveLength(1); }); it('gets an item from local storage', function () { storage.setItem(key, item); expect(storage.getItem(key)).toEqual(item); }); it('removes an item from local storage and returns it', function () { storage.setItem(key, item); expect(storage.removeItem(key)).toEqual(item); expect(localStorage).toHaveLength(0); }); it('supports custom prefixes', function () { storage = new browser_storage_service_1.BrowserStorageService(localStorage, prefix); storage.setItem(key, item); expect(localStorage).toHaveLength(1); expect(localStorage.getItem(key)).toBeNull(); expect(Object.keys(localStorage).filter(function (key) { return key.indexOf(prefix) === 0; })).toHaveLength(1); expect(storage.getItem(key)).toEqual(item); expect(storage.removeItem(key)).toEqual(item); expect(localStorage).toHaveLength(0); }); it('supports ttl', function () { storage.setItem(key, item, 50); expect(storage.getItem(key)).toEqual(item); Date.now = jest.fn(function () { return startingTimestamp + 100; }); expect(storage.getItem(key)).toBeNull(); }); it('removes expired items without explicitly getting them', function () { storage.setItem(key, item, 50); storage.setItem(anotherKey, item); expect(storage.getItem(key)).toEqual(item); expect(storage.getItem(anotherKey)).toEqual(item); Date.now = jest.fn(function () { return startingTimestamp + 100; }); // Unexpired item still exists expect(storage.getItem(anotherKey)).toEqual(item); // Expired item is removed from storage without actively getting it expect(localStorage).toHaveLength(1); }); it('clears all the items', function () { storage.setItem(key, item); storage.setItem(anotherKey, item); expect(storage.clear()).toEqual(2); expect(localStorage).toHaveLength(0); }); it('does not allow you to save undefined values', function () { storage.setItem(key, undefined); expect(localStorage).toHaveLength(0); }); it('allows you to save null values', function () { storage.setItem(key, null); expect(storage.getItem(key)).toBeNull(); }); it('returns null if you try to retrieve a non valid JSON item', function () { localStorage.setItem("empathy-".concat(key), '{a: 1}'); expect(localStorage).toHaveLength(1); expect(storage.getItem(key)).toBeNull(); }); }); //# sourceMappingURL=browser-storage-service.spec.js.map