-
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
81 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
import { Updater, defineState } from "../../src/helper/state"; | ||
|
||
describe("defineState", () => { | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
let storage: any; | ||
|
||
beforeEach(() => { | ||
storage = { | ||
get: vi.fn(), | ||
put: vi.fn(), | ||
}; | ||
}); | ||
|
||
afterEach(() => { | ||
vi.resetAllMocks(); | ||
}); | ||
|
||
it("set infered type correctly", async () => { | ||
const [get, set] = await defineState(storage, "key", "value"); | ||
|
||
expectTypeOf(get).toEqualTypeOf<() => Promise<string>>(); | ||
expectTypeOf(set).toEqualTypeOf< | ||
(value: string | Updater<string>) => Promise<string> | ||
>(); | ||
}); | ||
|
||
it("set complex type correctly", async () => { | ||
type ComplexType = | ||
| { | ||
status: "success"; | ||
data: { | ||
foo: string; | ||
bar: number; | ||
}; | ||
} | ||
| { | ||
status: "error"; | ||
message: string; | ||
}; | ||
|
||
const [get, set] = await defineState<ComplexType>(storage, "key", { | ||
status: "success", | ||
data: { | ||
foo: "foo", | ||
bar: 1, | ||
}, | ||
}); | ||
|
||
expectTypeOf(get).toEqualTypeOf<() => Promise<ComplexType>>(); | ||
expectTypeOf(set).toEqualTypeOf< | ||
(value: ComplexType | Updater<ComplexType>) => Promise<ComplexType> | ||
>(); | ||
|
||
await set({ | ||
status: "error", | ||
message: "error", | ||
}); | ||
}); | ||
|
||
it("should work geter", async () => { | ||
const [get] = await defineState(storage, "key", "value"); | ||
|
||
expect(await get()).toBe("value"); | ||
expect(storage.get).toBeCalledWith("key"); | ||
expect(storage.put).toBeCalledWith("key", "value"); | ||
}); | ||
|
||
it("should work setter (value)", async () => { | ||
const [_, set] = await defineState(storage, "key", "value"); | ||
|
||
await set("new value"); | ||
expect(storage.put).toBeCalledWith("key", "new value"); | ||
}); | ||
|
||
it("should work setter (updater)", async () => { | ||
const [_, set] = await defineState(storage, "key", "value"); | ||
|
||
await set((prev) => `${prev} + ${prev}`); | ||
expect(storage.put).toBeCalledWith("key", "value + value"); | ||
}); | ||
}); |