| 1 | import { delay } from "@clo/lib/async.ts"; |
| 2 | import { assertEquals } from "@std/assert"; |
| 3 | import { test, vi } from "vitest"; |
| 4 | import { createTestMutationClient } from "./share.ts"; |
| 5 | |
| 6 | test("passes context value to functions", async () => { |
| 7 | vi.useFakeTimers(); |
| 8 | const { client, successMessages } = createTestMutationClient(); |
| 9 | const calls: string[] = []; |
| 10 | |
| 11 | let values: number[] = []; |
| 12 | const mutTest = client.define({ |
| 13 | id: "test-1", |
| 14 | async mutate() { |
| 15 | values.push(this.contextValue); |
| 16 | calls.push("mutate"); |
| 17 | await delay(100); |
| 18 | }, |
| 19 | describe: ({ contextValue }) => { |
| 20 | values.push(contextValue); |
| 21 | calls.push("describe"); |
| 22 | return "test action"; |
| 23 | }, |
| 24 | describeResult: ({ contextValue }) => { |
| 25 | values.push(contextValue); |
| 26 | calls.push("describe"); |
| 27 | return "tested action"; |
| 28 | }, |
| 29 | optimistic: ({ contextValue, onRefetch, onRestore }) => { |
| 30 | values.push(contextValue); |
| 31 | onRefetch(async () => void calls.push("refetch")); |
| 32 | onRestore(async () => void calls.push("restore")); |
| 33 | calls.push("optimistic"); |
| 34 | }, |
| 35 | refetchOnSuccess: false, |
| 36 | }); |
| 37 | |
| 38 | mutTest.run(); |
| 39 | await vi.advanceTimersByTimeAsync(200); |
| 40 | |
| 41 | // Even with refetchOnSuccess=false, errors should still trigger refetch |
| 42 | assertEquals(calls.includes("refetch"), true, "refetch should be called on error"); |
| 43 | assertEquals(calls.includes("restore"), true, "restore should be called on error"); |
| 44 | assertEquals(successMessages.length, 1); |
| 45 | assertEquals(values, [42, 42, 42]); |
| 46 | }); |