import { describe, expect, it, vi } from "vitest" import { loadJson, performIfChanged, removeKey, saveJson } from "match-state-transport" describe("match state transport", () => { it("loads saved json from storage", () => { const storage = { getItem: vi.fn(() => '{"score":3}') } expect(loadJson(storage, "match-state:1:1001")).toEqual({ score: 3 }) expect(storage.getItem).toHaveBeenCalledWith("match-state:1:1001") }) it("returns null when stored json is invalid", () => { const storage = { getItem: vi.fn(() => "{not-json") } expect(loadJson(storage, "bad")).toBe(null) }) it("saves and removes json values in storage", () => { const storage = { setItem: vi.fn(), removeItem: vi.fn() } expect(saveJson(storage, "key", { score: 5 })).toBe(true) expect(storage.setItem).toHaveBeenCalledWith("key", '{"score":5}') expect(removeKey(storage, "key")).toBe(true) expect(storage.removeItem).toHaveBeenCalledWith("key") }) it("only performs subscription actions when the payload changes", () => { const subscription = { perform: vi.fn() } const firstSerialized = performIfChanged(subscription, "send_stat", { new_w1_stat: "T3" }, null) const secondSerialized = performIfChanged(subscription, "send_stat", { new_w1_stat: "T3" }, firstSerialized) const thirdSerialized = performIfChanged(subscription, "send_stat", { new_w1_stat: "T3 E1" }, secondSerialized) expect(subscription.perform).toHaveBeenCalledTimes(2) expect(subscription.perform).toHaveBeenNthCalledWith(1, "send_stat", { new_w1_stat: "T3" }) expect(subscription.perform).toHaveBeenNthCalledWith(2, "send_stat", { new_w1_stat: "T3 E1" }) expect(firstSerialized).toBe('{"new_w1_stat":"T3"}') expect(secondSerialized).toBe(firstSerialized) expect(thirdSerialized).toBe('{"new_w1_stat":"T3 E1"}') }) })