Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useLocalStorage.hook.browser.test.tsx

51 lines1.4 KB

1import * as Schema from "effect/Schema";
2import { act, createElement, useEffect } from "react";
3import { createRoot, type Root } from "react-dom/client";
4import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5​
6import { useLocalStorage } from "./useLocalStorage";
7​
8const KEY = "corrupt-key";
9let root: Root;
10let current: ReturnType<typeof useLocalStorage<number, number>>;
11​
12function Probe() {
13 const result = useLocalStorage(KEY, 0, Schema.Number);
14 useEffect(() => {
15 current = result;
16 });
17 return null;
19​
20beforeEach(async () => {
21 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
22 vi.spyOn(console, "error").mockImplementation(() => {});
23 localStorage.setItem(KEY, JSON.stringify("not a number"));
24 root = createRoot(document.createElement("div"));
25 await act(() => root.render(createElement(Probe)));
26});
27​
28afterEach(async () => {
29 await act(() => root.unmount());
30 localStorage.clear();
31 vi.restoreAllMocks();
32 vi.unstubAllGlobals();
33});
34​
35describe("useLocalStorage with a stored value that fails decode", () => {
36 it("replaces it with a plain write", async () => {
37 expect(current[0]).toBe(0);
38​
39 await act(() => current[1](42));
40​
41 expect(localStorage.getItem(KEY)).toBe("42");
42 expect(current[0]).toBe(42);
43 });
44​
45 it("runs an updater from the initial value", async () => {
46 await act(() => current[1]((value) => value + 1));
47​
48 expect(localStorage.getItem(KEY)).toBe("1");
49 expect(current[0]).toBe(1);
50 });
51});