1 import localStorageWithExpiry from '../../lib/api/helpers/localStorageWithExpiry';
3 describe('localStorageWithExpiry', () => {
4 let originalDateNow: typeof Date.now;
5 const mockedDateNow = 10;
8 originalDateNow = Date.now;
9 Date.now = () => mockedDateNow;
13 Date.now = originalDateNow;
14 window.localStorage.clear();
17 describe('storeData', () => {
18 it('should store data with an expiration time', async () => {
19 const key = 'test-key';
20 const value = 'test-value';
21 const expirationInMs = 1000;
22 localStorageWithExpiry.storeData(key, value, expirationInMs);
24 const results = JSON.parse(window.localStorage.getItem(key) || '');
25 expect(results.value).toEqual(value);
26 expect(results.expiresAt).toEqual(mockedDateNow + expirationInMs);
30 describe('getData', () => {
31 it('should return data if it exists and has not expired', async () => {
32 const key = 'test-key';
33 const value = 'test-value';
34 const expirationInMs = 1000;
35 localStorageWithExpiry.storeData(key, value, expirationInMs);
36 expect(localStorageWithExpiry.getData(key)).toBe(value);
39 it('should return null if data does not exist', async () => {
40 const key = 'test-key';
41 expect(localStorageWithExpiry.getData(key)).toBe(null);
44 it('should return null if data has expired', async () => {
45 const key = 'test-key';
46 const value = 'test-value';
47 const expirationInMs = -1;
48 localStorageWithExpiry.storeData(key, value, expirationInMs);
49 expect(localStorageWithExpiry.getData(key)).toBe(null);
53 describe('deleteData', () => {
54 it('should remove data from storage', async () => {
55 const key = 'test-key';
56 const value = 'test-value';
57 localStorageWithExpiry.storeData(key, value);
59 expect(JSON.parse(window.localStorage.getItem(key) || '').value).toEqual(value);
61 localStorageWithExpiry.deleteData(key);
63 expect(window.localStorage.getItem(key)).toEqual(null);
67 describe('deleteDataIfExpired', () => {
68 it('should remove data from storage only if it is expired', async () => {
69 const key = 'test-key';
70 const value = 'test-value';
71 localStorageWithExpiry.storeData(key, value);
72 expect(JSON.parse(window.localStorage.getItem(key) || '').value).toEqual(value);
75 localStorageWithExpiry.deleteDataIfExpired(key);
76 expect(JSON.parse(window.localStorage.getItem(key) || '').value).toEqual(value);
79 localStorageWithExpiry.storeData(key, value, -1);
80 localStorageWithExpiry.deleteDataIfExpired(key);
81 expect(window.localStorage.getItem(key)).toEqual(null);