|
| 1 | +import { describe, it, expect, beforeEach, test, vi } from "vitest"; |
| 2 | +import { createTypedStore } from "../zustand"; |
| 3 | + |
| 4 | +describe("createTypedStore", () => { |
| 5 | + interface TestStore { |
| 6 | + count: number; |
| 7 | + name: string; |
| 8 | + set: <K extends keyof TestStore>(key: K, value: TestStore[K]) => void; |
| 9 | + get: <K extends keyof TestStore>(key: K) => TestStore[K]; |
| 10 | + } |
| 11 | + |
| 12 | + let useStore: ReturnType<typeof createTypedStore<TestStore>>; |
| 13 | + let store: TestStore; |
| 14 | + |
| 15 | + beforeEach(() => { |
| 16 | + useStore = createTypedStore<TestStore>(); |
| 17 | + useStore.setState({ count: 0, name: "Test" }); |
| 18 | + store = useStore.getState(); |
| 19 | + }); |
| 20 | + |
| 21 | + test("should set and get values correctly", () => { |
| 22 | + store.set("count", 5); |
| 23 | + expect(store.get("count")).toBe(5); |
| 24 | + |
| 25 | + store.set("name", "Updated"); |
| 26 | + expect(store.get("name")).toBe("Updated"); |
| 27 | + }); |
| 28 | + |
| 29 | + test("should update state without affecting other properties", () => { |
| 30 | + store.set("count", 10); |
| 31 | + expect(store.get("count")).toBe(10); |
| 32 | + expect(store.get("name")).toBe("Test"); |
| 33 | + }); |
| 34 | + |
| 35 | + test("should return the current state", () => { |
| 36 | + const state = useStore.getState(); |
| 37 | + expect(state).toEqual( |
| 38 | + expect.objectContaining({ count: 0, name: "Test" }) |
| 39 | + ); |
| 40 | + }); |
| 41 | + |
| 42 | + test("should update state using setState", () => { |
| 43 | + useStore.setState({ count: 20, name: "New Name" }); |
| 44 | + store = useStore.getState(); |
| 45 | + expect(store.get("count")).toBe(20); |
| 46 | + expect(store.get("name")).toBe("New Name"); |
| 47 | + }); |
| 48 | + |
| 49 | + test("should subscribe to state changes", () => { |
| 50 | + const listener = vi.fn(); |
| 51 | + const unsubscribe = useStore.subscribe(listener); |
| 52 | + |
| 53 | + store.set("count", 15); |
| 54 | + expect(listener).toHaveBeenCalledTimes(1); |
| 55 | + |
| 56 | + store.set("name", "Another"); |
| 57 | + expect(listener).toHaveBeenCalledTimes(2); |
| 58 | + |
| 59 | + unsubscribe(); |
| 60 | + store.set("count", 25); |
| 61 | + expect(listener).toHaveBeenCalledTimes(2); |
| 62 | + }); |
| 63 | +}); |
0 commit comments