|
| 1 | +import { getLocalStorageItem, setLocalStorageItem, removeLocalStorageItem } from "./localStorage"; |
| 2 | + |
| 3 | +describe("localStorage tests", () => { |
| 4 | + beforeEach(() => { |
| 5 | + localStorage.clear(); |
| 6 | + jest.clearAllMocks(); |
| 7 | + }); |
| 8 | + |
| 9 | + test("getLocalStorageItem not existing", () => { |
| 10 | + expect(getLocalStorageItem("test")).toBeUndefined(); |
| 11 | + }); |
| 12 | + |
| 13 | + test("getLocalStorageItem existing", () => { |
| 14 | + const testData = { field1: "hello", field2: "world" }; |
| 15 | + localStorage.setItem("test", JSON.stringify({ data: testData })); |
| 16 | + expect(getLocalStorageItem("test")).toEqual(testData); |
| 17 | + }); |
| 18 | + |
| 19 | + test("getLocalStorageItem expired", () => { |
| 20 | + const expirationDate = new Date(new Date().getTime() - 1); |
| 21 | + localStorage.setItem("test", JSON.stringify({ data: true, expirationDate: expirationDate.toISOString() })); |
| 22 | + expect(localStorage.length).toBe(1); |
| 23 | + expect(getLocalStorageItem("test")).toBeUndefined(); |
| 24 | + expect(localStorage.length).toBe(0); |
| 25 | + }); |
| 26 | + |
| 27 | + test("setLocalStorageItem without expiration", () => { |
| 28 | + const testData = { field1: "hello", field2: "world" }; |
| 29 | + setLocalStorageItem("test", testData); |
| 30 | + expect(localStorage.length).toBe(1); |
| 31 | + expect(localStorage.getItem("test")).toBe(JSON.stringify({ data: testData })); |
| 32 | + }); |
| 33 | + |
| 34 | + test("setLocalStorageItem with expiration", () => { |
| 35 | + const expirationDate = new Date(2050, 1, 1, 16, 30, 45, 123); |
| 36 | + setLocalStorageItem("test", true, expirationDate); |
| 37 | + expect(localStorage.length).toBe(1); |
| 38 | + expect(localStorage.getItem("test")).toBe(JSON.stringify({ data: true, expirationDate: expirationDate.toISOString() })); |
| 39 | + }); |
| 40 | + |
| 41 | + test("removeLocalStorageItem", () => { |
| 42 | + localStorage.setItem("test", JSON.stringify({ data: true })); |
| 43 | + expect(localStorage.length).toBe(1); |
| 44 | + removeLocalStorageItem("test"); |
| 45 | + expect(localStorage.length).toBe(0); |
| 46 | + }); |
| 47 | +}); |
0 commit comments