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