| 1 | import { assertEquals } from "@std/assert"; |
| 2 | import { act, render, screen } from "@testing-library/react"; |
| 3 | import { userEvent } from "@testing-library/user-event"; |
| 4 | import { type FC, type MouseEventHandler, type ReactNode, StrictMode } from "react"; |
| 5 | import { renderToString } from "react-dom/server"; |
| 6 | import { test, vi } from "vitest"; |
| 7 | import { MutationClient } from "../src/client.ts"; |
| 8 | import { createMutationButton, useMutate } from "../src/react.ts"; |
| 9 | import { createTestMutationClient, IterableStream } from "./share.ts"; |
| 10 | |
| 11 | test("useMutate - global error and success handling", async () => { |
| 12 | vi.useFakeTimers({ shouldAdvanceTime: true }); |
| 13 | const user = userEvent.setup({ delay: null }); |
| 14 | |
| 15 | const { client, successMessages, errorMessages } = createTestMutationClient(); |
| 16 | const s = new IterableStream<string>(); |
| 17 | |
| 18 | const mutTest = client.define({ |
| 19 | id: "test-1", |
| 20 | mutate: async () => { |
| 21 | return (await s.next()).value; |
| 22 | }, |
| 23 | describe: "Test the action", |
| 24 | describeResult: "Tested the action", |
| 25 | optimistic: () => {}, |
| 26 | }); |
| 27 | |
| 28 | let renders: Array<{ isMutating: boolean; isPending: boolean }> = []; |
| 29 | function TestComponent() { |
| 30 | const { run, isMutating, isPending } = useMutate(mutTest); |
| 31 | renders.push({ isMutating, isPending }); |
| 32 | |
| 33 | return ( |
| 34 | <> |
| 35 | <button |
| 36 | data-testid="a" |
| 37 | onClick={() => { |
| 38 | run(); |
| 39 | }} |
| 40 | > |
| 41 | button |
| 42 | </button> |
| 43 | </> |
| 44 | ); |
| 45 | } |
| 46 | |
| 47 | render(<TestComponent />); |
| 48 | // initial state |
| 49 | assertEquals(renders, [{ isMutating: false, isPending: false }]); |
| 50 | assertEquals(successMessages, []); |
| 51 | assertEquals(errorMessages, []); |
| 52 | renders = []; |
| 53 | vi.runAllTimers(); |
| 54 | |
| 55 | // mutation 1 |
| 56 | await act(() => user.click(screen.getByTestId("a"))); |
| 57 | assertEquals(renders, [{ isMutating: true, isPending: false }]); |
| 58 | renders = []; |
| 59 | await act(() => vi.advanceTimersByTime(150)); |
| 60 | assertEquals(renders, []); |
| 61 | await act(() => vi.advanceTimersByTime(50)); |
| 62 | assertEquals(renders, [{ isMutating: true, isPending: true }]); |
| 63 | renders = []; |
| 64 | assertEquals(successMessages, []); |
| 65 | assertEquals(errorMessages, []); |
| 66 | await act(async () => { |
| 67 | s.push("ok"); |
| 68 | vi.advanceTimersByTime(100); |
| 69 | }); |
| 70 | assertEquals(successMessages, ["Tested the action"]); |
| 71 | assertEquals(errorMessages, []); |
| 72 | assertEquals(renders, [{ isMutating: false, isPending: false }]); |
| 73 | renders = []; |
| 74 | |
| 75 | // mutation 2 |
| 76 | await act(() => user.click(screen.getByTestId("a"))); |
| 77 | assertEquals(renders, [{ isMutating: true, isPending: false }]); |
| 78 | renders = []; |
| 79 | await act(() => vi.advanceTimersByTime(150)); |
| 80 | assertEquals(renders, []); |
| 81 | await act(() => vi.advanceTimersByTime(50)); |
| 82 | assertEquals(renders, [{ isMutating: true, isPending: true }]); |
| 83 | renders = []; |
| 84 | assertEquals(successMessages, ["Tested the action"]); |
| 85 | assertEquals(errorMessages, []); |
| 86 | const error1 = new Error("damn!"); |
| 87 | await act(async () => { |
| 88 | s.throw(error1); |
| 89 | vi.advanceTimersByTime(100); |
| 90 | }); |
| 91 | assertEquals(successMessages, ["Tested the action"]); |
| 92 | assertEquals(errorMessages, [ |
| 93 | { error: error1, message: "Could not test the action: damn!" }, |
| 94 | ]); |
| 95 | }); |
| 96 | |
| 97 | test("useMutate - a failure before the pending delay never leaves isPending stuck", async () => { |
| 98 | vi.useFakeTimers({ shouldAdvanceTime: true }); |
| 99 | const user = userEvent.setup({ delay: null }); |
| 100 | |
| 101 | const { client } = createTestMutationClient(); |
| 102 | const s = new IterableStream<string>(); |
| 103 | |
| 104 | const mutTest = client.define({ |
| 105 | id: "test-fast-failure", |
| 106 | mutate: async () => { |
| 107 | return (await s.next()).value; |
| 108 | }, |
| 109 | describe: "Test the action", |
| 110 | describeResult: null, |
| 111 | optimistic: () => {}, |
| 112 | }); |
| 113 | |
| 114 | let state = {}; |
| 115 | function TestComponent() { |
| 116 | const { run, isMutating, isPending, errorMessage } = useMutate(mutTest); |
| 117 | state = { isMutating, isPending, errorMessage }; |
| 118 | return ( |
| 119 | <button data-testid="a" onClick={() => run()}> |
| 120 | button |
| 121 | </button> |
| 122 | ); |
| 123 | } |
| 124 | |
| 125 | render(<TestComponent />); |
| 126 | await act(() => user.click(screen.getByTestId("a"))); |
| 127 | await act(async () => { |
| 128 | s.throw(new Error("damn!")); |
| 129 | vi.advanceTimersByTime(50); |
| 130 | }); |
| 131 | await act(() => vi.advanceTimersByTime(500)); |
| 132 | assertEquals(state, { |
| 133 | isMutating: false, |
| 134 | isPending: false, |
| 135 | errorMessage: "Could not test the action: damn!", |
| 136 | }); |
| 137 | }); |
| 138 | |
| 139 | test("useMutate - swapping the mutation within the pending delay never sets isPending", async () => { |
| 140 | vi.useFakeTimers({ shouldAdvanceTime: true }); |
| 141 | const user = userEvent.setup({ delay: null }); |
| 142 | |
| 143 | const { client } = createTestMutationClient(); |
| 144 | const s = new IterableStream<string>(); |
| 145 | const define = (id: string) => |
| 146 | client.define({ |
| 147 | id, |
| 148 | mutate: async () => { |
| 149 | return (await s.next()).value; |
| 150 | }, |
| 151 | describe: "Test the action", |
| 152 | describeResult: null, |
| 153 | optimistic: () => {}, |
| 154 | }); |
| 155 | const mutA = define("test-swap-a"); |
| 156 | const mutB = define("test-swap-b"); |
| 157 | |
| 158 | let isPending = false; |
| 159 | function TestComponent({ mutation }: { mutation: typeof mutA }) { |
| 160 | const state = useMutate(mutation); |
| 161 | isPending = state.isPending; |
| 162 | return ( |
| 163 | <button data-testid="a" onClick={() => state.run()}> |
| 164 | button |
| 165 | </button> |
| 166 | ); |
| 167 | } |
| 168 | |
| 169 | const view = render(<TestComponent mutation={mutA} />); |
| 170 | await act(() => user.click(screen.getByTestId("a"))); |
| 171 | view.rerender(<TestComponent mutation={mutB} />); |
| 172 | await act(() => vi.advanceTimersByTime(500)); |
| 173 | assertEquals(isPending, false); |
| 174 | }); |
| 175 | |
| 176 | test("useMutate - runWithOptions on another key clears the pending delay from run", async () => { |
| 177 | vi.useFakeTimers({ shouldAdvanceTime: true }); |
| 178 | const user = userEvent.setup({ delay: null }); |
| 179 | |
| 180 | const { client } = createTestMutationClient(); |
| 181 | |
| 182 | const mutTest = client.define({ |
| 183 | id: "test-pending-handoff", |
| 184 | mutate: (id: number) => id === 1 ? new Promise<string>(() => {}) : Promise.resolve("ok"), |
| 185 | key: ({ args: [id] }) => String(id), |
| 186 | describe: "Test the action", |
| 187 | describeResult: null, |
| 188 | optimistic: () => {}, |
| 189 | refetchOnSuccess: false, |
| 190 | }); |
| 191 | |
| 192 | let isPending = false; |
| 193 | function TestComponent() { |
| 194 | const state = useMutate(mutTest); |
| 195 | isPending = state.isPending; |
| 196 | return ( |
| 197 | <> |
| 198 | <button data-testid="a" onClick={() => state.run(1)}>a</button> |
| 199 | <button data-testid="b" onClick={() => state.runWithOptions(2, {})}>b</button> |
| 200 | </> |
| 201 | ); |
| 202 | } |
| 203 | |
| 204 | render(<TestComponent />); |
| 205 | await act(() => user.click(screen.getByTestId("a"))); |
| 206 | await act(() => user.click(screen.getByTestId("b"))); |
| 207 | await act(() => vi.advanceTimersByTime(500)); |
| 208 | assertEquals(isPending, false); |
| 209 | }); |
| 210 | |
| 211 | test("useMutate - local error and success handling", async () => { |
| 212 | vi.useFakeTimers({ shouldAdvanceTime: true }); |
| 213 | const user = userEvent.setup({ delay: null }); |
| 214 | |
| 215 | const { client, successMessages, errorMessages } = createTestMutationClient(); |
| 216 | const s = new IterableStream<string>(); |
| 217 | |
| 218 | const mutTest = client.define({ |
| 219 | id: "test-2", |
| 220 | mutate: async () => { |
| 221 | return (await s.next()).value; |
| 222 | }, |
| 223 | describe: "Test the action", |
| 224 | describeResult: "Tested the action", |
| 225 | optimistic: () => {}, |
| 226 | }); |
| 227 | |
| 228 | let renders: Array< |
| 229 | { |
| 230 | isMutating: boolean; |
| 231 | isPending: boolean; |
| 232 | result: string | undefined; |
| 233 | error: unknown; |
| 234 | errorMessage: string | undefined; |
| 235 | isSuccess: boolean; |
| 236 | isError: boolean; |
| 237 | isOptimisticData: boolean; |
| 238 | } |
| 239 | > = []; |
| 240 | function TestComponent() { |
| 241 | const { run, clear, isMutating, isPending, result, error, errorMessage, isSuccess, isError, isOptimisticData } = |
| 242 | useMutate( |
| 243 | mutTest, |
| 244 | ); |
| 245 | renders.push({ isMutating, isPending, result, error, errorMessage, isSuccess, isError, isOptimisticData }); |
| 246 | |
| 247 | return ( |
| 248 | <> |
| 249 | <button |
| 250 | data-testid="a" |
| 251 | onClick={() => { |
| 252 | run(); |
| 253 | }} |
| 254 | > |
| 255 | button |
| 256 | </button> |
| 257 | <button |
| 258 | data-testid="b" |
| 259 | onClick={() => { |
| 260 | clear(); |
| 261 | }} |
| 262 | > |
| 263 | clear |
| 264 | </button> |
| 265 | </> |
| 266 | ); |
| 267 | } |
| 268 | |
| 269 | render(<TestComponent />); |
| 270 | // initial state |
| 271 | assertEquals(renders, [{ |
| 272 | error: undefined, |
| 273 | errorMessage: undefined, |
| 274 | isError: false, |
| 275 | isMutating: false, |
| 276 | isOptimisticData: false, |
| 277 | isPending: false, |
| 278 | isSuccess: false, |
| 279 | result: undefined, |
| 280 | }]); |
| 281 | assertEquals(successMessages, []); |
| 282 | assertEquals(errorMessages, []); |
| 283 | renders = []; |
| 284 | vi.runAllTimers(); |
| 285 | |
| 286 | // mutation 1 - success |
| 287 | await act(() => user.click(screen.getByTestId("a"))); |
| 288 | assertEquals(renders, [{ |
| 289 | error: undefined, |
| 290 | errorMessage: undefined, |
| 291 | isError: false, |
| 292 | isMutating: true, |
| 293 | isOptimisticData: true, |
| 294 | isPending: false, |
| 295 | isSuccess: false, |
| 296 | result: undefined, |
| 297 | }]); |
| 298 | renders = []; |
| 299 | await act(() => vi.advanceTimersByTime(150)); |
| 300 | assertEquals(renders, []); |
| 301 | await act(() => vi.advanceTimersByTime(50)); |
| 302 | assertEquals(renders, [{ |
| 303 | error: undefined, |
| 304 | errorMessage: undefined, |
| 305 | isError: false, |
| 306 | isMutating: true, |
| 307 | isOptimisticData: true, |
| 308 | isPending: true, |
| 309 | isSuccess: false, |
| 310 | result: undefined, |
| 311 | }]); |
| 312 | renders = []; |
| 313 | assertEquals(successMessages, []); |
| 314 | assertEquals(errorMessages, []); |
| 315 | await act(async () => { |
| 316 | s.push("ok"); |
| 317 | vi.advanceTimersByTime(100); |
| 318 | }); |
| 319 | assertEquals(successMessages, []); |
| 320 | assertEquals(errorMessages, []); |
| 321 | assertEquals(renders, [{ |
| 322 | error: undefined, |
| 323 | errorMessage: undefined, |
| 324 | isError: false, |
| 325 | isMutating: false, |
| 326 | isOptimisticData: false, |
| 327 | isPending: false, |
| 328 | isSuccess: true, |
| 329 | result: "ok", |
| 330 | }]); |
| 331 | renders = []; |
| 332 | |
| 333 | // clear state |
| 334 | vi.runAllTimers(); |
| 335 | await act(() => user.click(screen.getByTestId("b"))); |
| 336 | assertEquals(renders, [{ |
| 337 | error: undefined, |
| 338 | errorMessage: undefined, |
| 339 | isError: false, |
| 340 | isMutating: false, |
| 341 | isOptimisticData: false, |
| 342 | isPending: false, |
| 343 | isSuccess: false, |
| 344 | result: undefined, |
| 345 | }]); |
| 346 | renders = []; |
| 347 | await act(() => user.click(screen.getByTestId("b"))); |
| 348 | assertEquals(renders, []); // nothing changed |
| 349 | renders = []; |
| 350 | |
| 351 | // mutation 2 - failure |
| 352 | await act(() => user.click(screen.getByTestId("a"))); |
| 353 | assertEquals(renders, [{ |
| 354 | error: undefined, |
| 355 | errorMessage: undefined, |
| 356 | isError: false, |
| 357 | isMutating: true, |
| 358 | isOptimisticData: true, |
| 359 | isPending: false, |
| 360 | isSuccess: false, |
| 361 | result: undefined, |
| 362 | }]); |
| 363 | renders = []; |
| 364 | await act(() => vi.advanceTimersByTime(150)); |
| 365 | assertEquals(renders, []); |
| 366 | await act(() => vi.advanceTimersByTime(50)); |
| 367 | assertEquals(renders, [{ |
| 368 | error: undefined, |
| 369 | errorMessage: undefined, |
| 370 | isError: false, |
| 371 | isMutating: true, |
| 372 | isOptimisticData: true, |
| 373 | isPending: true, |
| 374 | isSuccess: false, |
| 375 | result: undefined, |
| 376 | }]); |
| 377 | renders = []; |
| 378 | const error1 = new Error("damn!"); |
| 379 | await act(async () => { |
| 380 | s.throw(error1); |
| 381 | vi.advanceTimersByTime(100); |
| 382 | }); |
| 383 | assertEquals(renders, [{ |
| 384 | error: error1, |
| 385 | errorMessage: "Could not test the action: damn!", |
| 386 | isError: true, |
| 387 | isMutating: false, |
| 388 | isOptimisticData: false, |
| 389 | isPending: false, |
| 390 | isSuccess: false, |
| 391 | result: undefined, |
| 392 | }]); |
| 393 | assertEquals(successMessages, []); |
| 394 | assertEquals(errorMessages, []); |
| 395 | }); |
| 396 | |
| 397 | test("MutationButton should allow args={null} to disable mutation runs", async () => { |
| 398 | const user = userEvent.setup({ delay: null }); |
| 399 | const { client } = createTestMutationClient(); |
| 400 | const mutate = vi.fn(async (value: number) => value + 1); |
| 401 | |
| 402 | const mutTest = client.define({ |
| 403 | id: "test-3", |
| 404 | mutate, |
| 405 | describe: "Test the action", |
| 406 | describeResult: "Tested the action", |
| 407 | optimistic: () => {}, |
| 408 | }); |
| 409 | |
| 410 | const MutationButtonBase: FC<{ |
| 411 | children?: ReactNode; |
| 412 | disabled?: boolean; |
| 413 | isPending: boolean; |
| 414 | onClick: MouseEventHandler<HTMLElement> | undefined; |
| 415 | }> = function MutationButtonBase({ |
| 416 | children, |
| 417 | disabled, |
| 418 | isPending, |
| 419 | onClick, |
| 420 | }) { |
| 421 | return ( |
| 422 | <button data-testid="a" disabled={disabled || isPending} onClick={onClick}> |
| 423 | {children} |
| 424 | </button> |
| 425 | ); |
| 426 | }; |
| 427 | const MutationButton = createMutationButton(MutationButtonBase); |
| 428 | |
| 429 | render( |
| 430 | <MutationButton mutation={mutTest} args={null}> |
| 431 | button |
| 432 | </MutationButton>, |
| 433 | ); |
| 434 | |
| 435 | assertEquals((screen.getByTestId("a") as HTMLButtonElement).disabled, true); |
| 436 | await act(() => user.click(screen.getByTestId("a"))); |
| 437 | |
| 438 | assertEquals(mutate.mock.calls, []); |
| 439 | }); |
| 440 | |
| 441 | function countedAllowedMutation() { |
| 442 | let activeSubscriptions = 0; |
| 443 | const subscribers = new Set<() => void>(); |
| 444 | let allowed = true; |
| 445 | const sub = (cb: () => void) => { |
| 446 | activeSubscriptions++; |
| 447 | subscribers.add(cb); |
| 448 | return () => { |
| 449 | activeSubscriptions--; |
| 450 | subscribers.delete(cb); |
| 451 | }; |
| 452 | }; |
| 453 | const client = new MutationClient({ |
| 454 | context: {}, |
| 455 | userContext: { get: () => null, sub }, |
| 456 | getOptimisticHelpers: () => ({}), |
| 457 | reportError: () => {}, |
| 458 | }); |
| 459 | const mutTest = client.define({ |
| 460 | id: "test-allowed-subscription", |
| 461 | mutate: async () => "ok", |
| 462 | describe: "Test", |
| 463 | describeResult: null, |
| 464 | optimistic: () => {}, |
| 465 | isAllowed: { get: () => allowed, sub }, |
| 466 | }); |
| 467 | const setAllowed = (next: boolean) => { |
| 468 | allowed = next; |
| 469 | subscribers.forEach((cb) => cb()); |
| 470 | }; |
| 471 | return { mutTest, setAllowed, activeSubscriptions: () => activeSubscriptions }; |
| 472 | } |
| 473 | |
| 474 | test("server rendering never subscribes to allowed state", () => { |
| 475 | const { mutTest, activeSubscriptions } = countedAllowedMutation(); |
| 476 | function App() { |
| 477 | useMutate(mutTest); |
| 478 | return null; |
| 479 | } |
| 480 | for (let i = 0; i < 3; i++) renderToString(<App />); |
| 481 | assertEquals(activeSubscriptions(), 0); |
| 482 | }); |
| 483 | |
| 484 | test("StrictMode keeps the allowed subscription alive", () => { |
| 485 | const { mutTest, setAllowed, activeSubscriptions } = countedAllowedMutation(); |
| 486 | let lastIsAllowed: boolean | null = null; |
| 487 | function App() { |
| 488 | lastIsAllowed = useMutate(mutTest).isAllowed; |
| 489 | return null; |
| 490 | } |
| 491 | const view = render( |
| 492 | <StrictMode> |
| 493 | <App /> |
| 494 | </StrictMode>, |
| 495 | ); |
| 496 | assertEquals(lastIsAllowed, true); |
| 497 | |
| 498 | act(() => setAllowed(false)); |
| 499 | assertEquals(lastIsAllowed, false); |
| 500 | |
| 501 | view.unmount(); |
| 502 | assertEquals(activeSubscriptions(), 0); |
| 503 | }); |