|
| 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 | + localStorage.setItem("test", '{"data":{"field1":"hello","field2":"world"}}'); |
| 15 | + expect(getLocalStorageItem("test")).toMatchObject({ field1: "hello", field2: "world" }); |
| 16 | + }); |
| 17 | + |
| 18 | + test("getLocalStorageItem expired", () => { |
| 19 | + const expiredDate = new Date(new Date().getTime() - 1); |
| 20 | + localStorage.setItem("test", `{"data":true,"expirationDate":"${expiredDate.toISOString()}"}`); |
| 21 | + expect(localStorage.length).toBe(1); |
| 22 | + expect(getLocalStorageItem("test")).toBeUndefined(); |
| 23 | + expect(localStorage.length).toBe(0); |
| 24 | + }); |
| 25 | + |
| 26 | + test("setLocalStorageItem without expiration", () => { |
| 27 | + setLocalStorageItem("test", { field1: "hello", field2: "world" }); |
| 28 | + expect(localStorage.length).toBe(1); |
| 29 | + expect(localStorage.getItem("test")).toBe('{"data":{"field1":"hello","field2":"world"}}'); |
| 30 | + }); |
| 31 | + |
| 32 | + test("setLocalStorageItem with expiration", () => { |
| 33 | + const expirationDate = new Date(2050, 1, 1, 16, 30, 45, 123); |
| 34 | + // Remove the system timezone to properly verify the serialized time |
| 35 | + const expirationDateWithoutTimezone = new Date(expirationDate.getTime() - expirationDate.getTimezoneOffset() * 60000); |
| 36 | + setLocalStorageItem("test", true, expirationDateWithoutTimezone); |
| 37 | + expect(localStorage.length).toBe(1); |
| 38 | + expect(localStorage.getItem("test")).toBe('{"data":true,"expirationDate":"2050-02-01T16:30:45.123Z"}'); |
| 39 | + }); |
| 40 | + |
| 41 | + test("removeLocalStorageItem", () => { |
| 42 | + localStorage.setItem("test", '{"data":true'); |
| 43 | + expect(localStorage.length).toBe(1); |
| 44 | + removeLocalStorageItem("test"); |
| 45 | + expect(localStorage.length).toBe(0); |
| 46 | + }); |
| 47 | +}); |
0 commit comments