From 93a4c66151f0c3195a5d5a5fd379547cb1da191a Mon Sep 17 00:00:00 2001 From: Antoine Niek Date: Wed, 18 Dec 2024 14:16:52 -0500 Subject: [PATCH] Add storage proxy test --- lib/core/regs/storage.test.js | 52 +++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 lib/core/regs/storage.test.js diff --git a/lib/core/regs/storage.test.js b/lib/core/regs/storage.test.js new file mode 100644 index 0000000..d30d8da --- /dev/null +++ b/lib/core/regs/storage.test.js @@ -0,0 +1,52 @@ +import { LocalStorageProxy } from "./storage"; + +describe("LocalStorageProxy", () => { + let windowSpy; + + let localStorageMock = { + getItem: jest.fn(), + setItem: jest.fn(), + removeItem: jest.fn(), + }; + + beforeEach(() => { + windowSpy = jest.spyOn(window, "window", "get"); + windowSpy.mockImplementation(() => ({ + localStorage: localStorageMock, + })); + }); + + afterEach(() => { + localStorageMock.getItem.mockClear(); + localStorageMock.setItem.mockClear(); + localStorageMock.removeItem.mockClear(); + windowSpy.mockRestore(); + }); + + it("proxies to underlying storage when consent granted", () => { + const storage = new LocalStorageProxy({ deviceAccess: true }); + + storage.getItem("key"); + expect(localStorageMock.getItem).toHaveBeenCalledWith("key"); + + storage.setItem("key", "value"); + expect(localStorageMock.setItem).toHaveBeenCalledWith("key", "value"); + + storage.removeItem("key"); + expect(localStorageMock.removeItem).toHaveBeenCalledWith("key"); + }); + + it("doesn't access underlying storage when consent not granted", () => { + const storage = new LocalStorageProxy({ deviceAccess: false }); + + const result = storage.getItem("key"); + expect(localStorageMock.getItem).not.toHaveBeenCalled(); + expect(result).toBeNull(); + + storage.setItem("key", "value"); + expect(localStorageMock.setItem).not.toHaveBeenCalled(); + + storage.removeItem("key"); + expect(localStorageMock.removeItem).not.toHaveBeenCalled(); + }); +});