forked from neolution-ch/javascript-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocalStorage.spec.ts
More file actions
56 lines (48 loc) · 2.1 KB
/
localStorage.spec.ts
File metadata and controls
56 lines (48 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { getLocalStorageItem, setLocalStorageItem, removeLocalStorageItem } from "./localStorage";
describe("localStorage tests", () => {
beforeEach(() => {
localStorage.clear();
jest.clearAllMocks();
});
test("localStorage not supported", () => {
const { localStorage } = global;
delete (global as Partial<typeof global>).localStorage;
expect(() => {
getLocalStorageItem("test");
}).toThrow("localStorage not supported");
global.localStorage = localStorage;
});
test("getLocalStorageItem not existing", () => {
expect(getLocalStorageItem("test")).toBeUndefined();
});
test("getLocalStorageItem existing", () => {
const testData = { field1: "hello", field2: "world" };
localStorage.setItem("test", JSON.stringify({ data: testData }));
expect(getLocalStorageItem("test")).toEqual(testData);
});
test("getLocalStorageItem expired", () => {
const expirationDate = new Date(Date.now() - 1);
localStorage.setItem("test", JSON.stringify({ data: true, expirationDate: expirationDate.toISOString() }));
expect(localStorage.length).toBe(1);
expect(getLocalStorageItem("test")).toBeUndefined();
expect(localStorage.length).toBe(0);
});
test("setLocalStorageItem without expiration", () => {
const testData = { field1: "hello", field2: "world" };
setLocalStorageItem("test", testData);
expect(localStorage.length).toBe(1);
expect(localStorage.getItem("test")).toBe(JSON.stringify({ data: testData }));
});
test("setLocalStorageItem with expiration", () => {
const expirationDate = new Date(2050, 1, 1, 16, 30, 45, 123);
setLocalStorageItem("test", true, expirationDate);
expect(localStorage.length).toBe(1);
expect(localStorage.getItem("test")).toBe(JSON.stringify({ data: true, expirationDate: expirationDate.toISOString() }));
});
test("removeLocalStorageItem", () => {
localStorage.setItem("test", JSON.stringify({ data: true }));
expect(localStorage.length).toBe(1);
removeLocalStorageItem("test");
expect(localStorage.length).toBe(0);
});
});