@hyper-fetch/react 9.5.0 → 9.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -159,7 +159,12 @@ describe("useFetch [ Methods ]", () => {
159
159
  const spy7 = vi.fn();
160
160
  const spy8 = vi.fn();
161
161
 
162
- const errorMock = mockRequest(request, { status: 400 });
162
+ let successMock = mockRequest(request, { status: 400 });
163
+ // Swapped on the response event, polling for the error state can lose the race with the retry timer
164
+ const unmountListener = client.requestManager.events.onResponse(() => {
165
+ unmountListener();
166
+ successMock = mockRequest(request);
167
+ });
163
168
  const response = renderUseFetch(request.setRetry(1).setRetryTime(100));
164
169
 
165
170
  act(() => {
@@ -173,8 +178,9 @@ describe("useFetch [ Methods ]", () => {
173
178
  response.result.current.onOfflineError(spy8);
174
179
  });
175
180
 
176
- await testErrorState(errorMock, response);
177
- const successMock = mockRequest(request);
181
+ await waitFor(() => {
182
+ expect(spy5).toHaveBeenCalledTimes(1);
183
+ });
178
184
  await testSuccessState(successMock, response);
179
185
 
180
186
  expect(spy1).toHaveBeenCalledTimes(2);
@@ -199,7 +199,12 @@ describe("useSubmit [ Methods ]", () => {
199
199
  const spy7 = vi.fn();
200
200
  const spy8 = vi.fn();
201
201
 
202
- const errorMock = mockRequest(request, { status: 400 });
202
+ let successMock = mockRequest(request, { status: 400 });
203
+ // Swapped on the response event, polling for the error state can lose the race with the retry timer
204
+ const unmountListener = client.requestManager.events.onResponse(() => {
205
+ unmountListener();
206
+ successMock = mockRequest(request);
207
+ });
203
208
  const response = renderUseSubmit(request.setRetry(1).setRetryTime(100));
204
209
 
205
210
  act(() => {
@@ -214,8 +219,9 @@ describe("useSubmit [ Methods ]", () => {
214
219
  response.result.current.submit();
215
220
  });
216
221
 
217
- await testErrorState(errorMock, response);
218
- const successMock = mockRequest(request);
222
+ await waitFor(() => {
223
+ expect(spy5).toHaveBeenCalledTimes(1);
224
+ });
219
225
  await testSuccessState(successMock, response);
220
226
 
221
227
  expect(spy1).toHaveBeenCalledTimes(2);
@@ -0,0 +1,625 @@
1
+ import type { OptimisticRollbackArgs, RequestInstance, RequestResponseEventType } from "@hyper-fetch/core";
2
+ import { Client, getErrorMessage, scopeKey } from "@hyper-fetch/core";
3
+ import { createHttpMockingServer } from "@hyper-fetch/testing";
4
+ import { act, renderHook, waitFor } from "@testing-library/react";
5
+ import { useSubmit } from "hooks/use-submit";
6
+ import { StrictMode } from "react";
7
+
8
+ const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
9
+
10
+ const SERVER_ITEM = "server";
11
+ const OPTIMISTIC_ITEM = "optimistic";
12
+ const INITIAL_LIST = [SERVER_ITEM];
13
+ const OPTIMISTIC_LIST = [SERVER_ITEM, OPTIMISTIC_ITEM];
14
+
15
+ /**
16
+ * Builds isolated client with a seeded list and a mutation which adds one item to it optimistically
17
+ */
18
+ const createSetup = () => {
19
+ const client = new Client({ url: "shared-base-url" });
20
+ const list = client.createRequest<{ response: string[] }>()({ endpoint: "/list" });
21
+
22
+ client.cache.set(list, {
23
+ data: INITIAL_LIST,
24
+ error: null,
25
+ status: 200,
26
+ success: true,
27
+ extra: client.adapter.defaultExtra,
28
+ retries: 0,
29
+ isCanceled: false,
30
+ isOffline: false,
31
+ willRetry: false,
32
+ addedTimestamp: Date.now(),
33
+ triggerTimestamp: Date.now(),
34
+ requestTimestamp: Date.now(),
35
+ // Garbage collector drops the entries with outdated timestamps
36
+ responseTimestamp: Date.now(),
37
+ });
38
+
39
+ const readList = () => client.cache.get<string[], unknown>(list.cacheKey)?.data;
40
+ const addItem = (item: string) => {
41
+ client.cache.update(list, (prev) => ({ data: [...(prev?.data ?? []), item] }));
42
+ };
43
+ const removeItem = (item: string) => {
44
+ client.cache.update(list, (prev) => ({ data: (prev?.data ?? []).filter((value) => value !== item) }));
45
+ };
46
+
47
+ const rollback = vi.fn((_args: OptimisticRollbackArgs<any>) => {
48
+ removeItem(OPTIMISTIC_ITEM);
49
+ });
50
+ const invalidate = vi.spyOn(client.cache, "invalidate");
51
+
52
+ const mutation = client
53
+ .createRequest<{ response: { ok: boolean } }>()({ endpoint: "/mutation", method: "POST" })
54
+ .setOptimistic(() => {
55
+ addItem(OPTIMISTIC_ITEM);
56
+ return { context: { item: OPTIMISTIC_ITEM }, rollback, invalidate: [list] };
57
+ });
58
+
59
+ const responses: RequestResponseEventType<RequestInstance>[] = [];
60
+ client.requestManager.events.onResponse((values) => {
61
+ responses.push(values);
62
+ });
63
+
64
+ const dispatcher = client.submitDispatcher;
65
+ const queryKey = scopeKey(mutation.queryKey, mutation.scope);
66
+ const abortKey = scopeKey(mutation.abortKey, mutation.scope);
67
+
68
+ return {
69
+ client,
70
+ list,
71
+ mutation,
72
+ rollback,
73
+ invalidate,
74
+ responses,
75
+ dispatcher,
76
+ queryKey,
77
+ abortKey,
78
+ readList,
79
+ addItem,
80
+ removeItem,
81
+ };
82
+ };
83
+
84
+ type Setup = ReturnType<typeof createSetup>;
85
+ type Mutation = Setup["mutation"];
86
+
87
+ const waitForResponses = async (setup: Setup, count: number) => {
88
+ await waitFor(() => {
89
+ expect(setup.responses).toHaveLength(count);
90
+ });
91
+ };
92
+
93
+ /**
94
+ * Starts the submit inside of act and exposes its promise
95
+ */
96
+ const startSubmit = (submit: (options?: any) => Promise<any>, options?: Record<string, unknown>) => {
97
+ let pending: Promise<any> = Promise.resolve();
98
+ act(() => {
99
+ pending = submit(options);
100
+ });
101
+ return pending;
102
+ };
103
+
104
+ const finishSubmit = async (pending: Promise<any>) => {
105
+ let result: any;
106
+ await act(async () => {
107
+ result = await pending;
108
+ });
109
+ return result;
110
+ };
111
+
112
+ const goOfflineOnFirstAttempt = (setup: Setup) => {
113
+ let isFirstAttempt = true;
114
+ return {
115
+ onRequestStart: () => {
116
+ if (isFirstAttempt) {
117
+ isFirstAttempt = false;
118
+ setup.client.appManager.setOnline(false);
119
+ }
120
+ },
121
+ };
122
+ };
123
+
124
+ type Scenario = {
125
+ name: string;
126
+ build?: (setup: Setup) => Mutation;
127
+ arrange: (setup: Setup, request: Mutation) => Record<string, unknown> | void;
128
+ drive?: (setup: Setup, request: Mutation) => Promise<void>;
129
+ settled?: (setup: Setup) => Promise<void>;
130
+ expected: {
131
+ list: string[];
132
+ invalidated: boolean;
133
+ callback: "onSubmitSuccess" | "onSubmitError" | "onSubmitAbort" | null;
134
+ rollback?: { reason: "error" | "abort" | "removed"; status?: number; errorMessage?: string };
135
+ };
136
+ };
137
+
138
+ const scenarios: Scenario[] = [
139
+ {
140
+ name: "success",
141
+ arrange: (_, request) => {
142
+ mockRequest(request, { data: { ok: true } });
143
+ },
144
+ expected: { list: OPTIMISTIC_LIST, invalidated: true, callback: "onSubmitSuccess" },
145
+ },
146
+ {
147
+ name: "final error",
148
+ arrange: (_, request) => {
149
+ mockRequest(request, { status: 400 });
150
+ },
151
+ expected: {
152
+ list: INITIAL_LIST,
153
+ invalidated: false,
154
+ callback: "onSubmitError",
155
+ rollback: { reason: "error", status: 400 },
156
+ },
157
+ },
158
+ {
159
+ name: "abort",
160
+ arrange: (_, request) => {
161
+ mockRequest(request, { delay: 100 });
162
+ return {
163
+ onRequestStart: () => {
164
+ request.abort();
165
+ },
166
+ };
167
+ },
168
+ expected: {
169
+ list: INITIAL_LIST,
170
+ invalidated: false,
171
+ callback: "onSubmitAbort",
172
+ rollback: { reason: "abort", errorMessage: getErrorMessage("abort").message },
173
+ },
174
+ },
175
+ {
176
+ name: "queue removal",
177
+ arrange: (setup, request) => {
178
+ mockRequest(request);
179
+ setup.dispatcher.stop(setup.queryKey);
180
+ return {
181
+ onBeforeSent: ({ requestId }: { requestId: string }) => {
182
+ // Listeners of the send call are attached right after this callback
183
+ queueMicrotask(() => {
184
+ setup.dispatcher.delete(setup.queryKey, requestId, setup.abortKey);
185
+ });
186
+ },
187
+ };
188
+ },
189
+ expected: { list: INITIAL_LIST, invalidated: false, callback: null, rollback: { reason: "removed" } },
190
+ },
191
+ {
192
+ name: "retry then success",
193
+ build: ({ mutation }) => mutation.setRetry(1).setRetryTime(10),
194
+ arrange: (setup, request) => {
195
+ mockRequest(request, { status: 400 });
196
+ const unmount = setup.client.requestManager.events.onResponse(() => {
197
+ unmount();
198
+ mockRequest(request, { data: { ok: true } });
199
+ });
200
+ },
201
+ expected: { list: OPTIMISTIC_LIST, invalidated: true, callback: "onSubmitSuccess" },
202
+ },
203
+ {
204
+ name: "retry then error",
205
+ build: ({ mutation }) => mutation.setRetry(1).setRetryTime(10),
206
+ arrange: (setup, request) => {
207
+ mockRequest(request, { status: 400 });
208
+ const unmount = setup.client.requestManager.events.onResponse(() => {
209
+ unmount();
210
+ mockRequest(request, { status: 500 });
211
+ });
212
+ },
213
+ expected: {
214
+ list: INITIAL_LIST,
215
+ invalidated: false,
216
+ callback: "onSubmitError",
217
+ rollback: { reason: "error", status: 500 },
218
+ },
219
+ },
220
+ {
221
+ name: "offline then success",
222
+ arrange: (setup, request) => {
223
+ mockRequest(request, { status: 400, delay: 30 });
224
+ return goOfflineOnFirstAttempt(setup);
225
+ },
226
+ drive: async (setup, request) => {
227
+ await waitForResponses(setup, 1);
228
+ expect(setup.rollback).not.toHaveBeenCalled();
229
+ expect(setup.readList()).toStrictEqual(OPTIMISTIC_LIST);
230
+ mockRequest(request, { data: { ok: true } });
231
+ act(() => {
232
+ setup.client.appManager.setOnline(true);
233
+ });
234
+ },
235
+ expected: { list: OPTIMISTIC_LIST, invalidated: true, callback: "onSubmitSuccess" },
236
+ },
237
+ {
238
+ name: "offline then error",
239
+ arrange: (setup, request) => {
240
+ mockRequest(request, { status: 400, delay: 30 });
241
+ return goOfflineOnFirstAttempt(setup);
242
+ },
243
+ drive: async (setup, request) => {
244
+ await waitForResponses(setup, 1);
245
+ expect(setup.rollback).not.toHaveBeenCalled();
246
+ expect(setup.readList()).toStrictEqual(OPTIMISTIC_LIST);
247
+ mockRequest(request, { status: 500 });
248
+ act(() => {
249
+ setup.client.appManager.setOnline(true);
250
+ });
251
+ },
252
+ expected: {
253
+ list: INITIAL_LIST,
254
+ invalidated: false,
255
+ callback: "onSubmitError",
256
+ rollback: { reason: "error", status: 500 },
257
+ },
258
+ },
259
+ ];
260
+
261
+ describe("useSubmit [ Optimistic settlement ]", () => {
262
+ beforeAll(() => {
263
+ startServer();
264
+ });
265
+
266
+ afterEach(() => {
267
+ resetMocks();
268
+ });
269
+
270
+ afterAll(() => {
271
+ stopServer();
272
+ });
273
+
274
+ describe("when settling the submitted request", () => {
275
+ it.each(scenarios)("should settle $name", async ({ build, arrange, drive, settled, expected }) => {
276
+ const setup = createSetup();
277
+ const request = build?.(setup) ?? setup.mutation;
278
+ const callback = vi.fn();
279
+ let sentRequest: RequestInstance | undefined;
280
+
281
+ const options = arrange(setup, request) ?? {};
282
+ const { result } = renderHook(() => useSubmit(request));
283
+ act(() => {
284
+ if (expected.callback) {
285
+ result.current[expected.callback](callback);
286
+ }
287
+ });
288
+
289
+ const pending = startSubmit(result.current.submit, {
290
+ ...options,
291
+ onBeforeSent: (data: { request: RequestInstance; requestId: string }) => {
292
+ sentRequest = data.request;
293
+ (options as { onBeforeSent?: (value: typeof data) => void }).onBeforeSent?.(data);
294
+ },
295
+ });
296
+
297
+ await drive?.(setup, request);
298
+ await finishSubmit(pending);
299
+ await settled?.(setup);
300
+
301
+ expect(setup.readList()).toStrictEqual(expected.list);
302
+
303
+ if (expected.invalidated) {
304
+ expect(setup.invalidate).toHaveBeenCalledTimes(1);
305
+ expect(setup.invalidate).toHaveBeenCalledWith(setup.list);
306
+ } else {
307
+ expect(setup.invalidate).not.toHaveBeenCalled();
308
+ }
309
+
310
+ if (expected.rollback) {
311
+ expect(setup.rollback).toHaveBeenCalledTimes(1);
312
+ const [args] = setup.rollback.mock.calls[0];
313
+ expect(args.reason).toBe(expected.rollback.reason);
314
+ expect(args.request).toBe(sentRequest);
315
+ if (expected.rollback.reason === "removed") {
316
+ expect(args).not.toHaveProperty("response");
317
+ }
318
+ if (expected.rollback.status) {
319
+ expect(args.response?.status).toBe(expected.rollback.status);
320
+ }
321
+ if (expected.rollback.errorMessage) {
322
+ expect(args.response?.error).toHaveProperty("message", expected.rollback.errorMessage);
323
+ }
324
+ } else {
325
+ expect(setup.rollback).not.toHaveBeenCalled();
326
+ }
327
+
328
+ if (expected.callback) {
329
+ await waitFor(() => {
330
+ expect(callback).toHaveBeenCalled();
331
+ });
332
+ const lastCall = callback.mock.calls.at(-1)?.[0];
333
+ expect(lastCall.mutationContext).toStrictEqual({ item: OPTIMISTIC_ITEM });
334
+ }
335
+ });
336
+
337
+ it("should report removal when aborting with the hook method", async () => {
338
+ const setup = createSetup();
339
+ mockRequest(setup.mutation, { delay: 100 });
340
+ const { result } = renderHook(() => useSubmit(setup.mutation));
341
+
342
+ const pending = startSubmit(result.current.submit, {
343
+ onRequestStart: () => {
344
+ result.current.abort();
345
+ },
346
+ });
347
+ await finishSubmit(pending);
348
+ await waitForResponses(setup, 1);
349
+
350
+ expect(setup.rollback).toHaveBeenCalledTimes(1);
351
+ expect(setup.rollback.mock.calls[0][0].reason).toBe("removed");
352
+ expect(setup.readList()).toStrictEqual(INITIAL_LIST);
353
+ });
354
+
355
+ it("should have the cache rolled back when onSubmitError fires", async () => {
356
+ const setup = createSetup();
357
+ mockRequest(setup.mutation, { status: 400 });
358
+ const { result } = renderHook(() => useSubmit(setup.mutation));
359
+ let listInCallback: string[] | null | undefined;
360
+
361
+ act(() => {
362
+ result.current.onSubmitError(() => {
363
+ listInCallback = setup.readList();
364
+ });
365
+ });
366
+ await finishSubmit(startSubmit(result.current.submit));
367
+
368
+ await waitFor(() => {
369
+ expect(listInCallback).toStrictEqual(INITIAL_LIST);
370
+ });
371
+ });
372
+
373
+ it("should fire callbacks when rollback throws", async () => {
374
+ const setup = createSetup();
375
+ setup.rollback.mockImplementation(() => {
376
+ throw new Error("Rollback failed");
377
+ });
378
+ mockRequest(setup.mutation, { status: 400 });
379
+ const { result } = renderHook(() => useSubmit(setup.mutation));
380
+ const onError = vi.fn();
381
+ const onFinished = vi.fn();
382
+
383
+ act(() => {
384
+ result.current.onSubmitError(onError);
385
+ result.current.onSubmitFinished(onFinished);
386
+ });
387
+ const response = await finishSubmit(startSubmit(result.current.submit));
388
+
389
+ expect(response.status).toBe(400);
390
+ expect(setup.rollback).toHaveBeenCalledTimes(1);
391
+ await waitFor(() => {
392
+ expect(onError).toHaveBeenCalledTimes(1);
393
+ expect(onFinished).toHaveBeenCalledTimes(1);
394
+ });
395
+ });
396
+ });
397
+
398
+ describe("when component unmounts while the request is pending", () => {
399
+ it("should roll back failed request", async () => {
400
+ const setup = createSetup();
401
+ mockRequest(setup.mutation, { status: 400, delay: 30 });
402
+ const { result, unmount } = renderHook(() => useSubmit(setup.mutation));
403
+
404
+ const pending = startSubmit(result.current.submit);
405
+ await waitFor(() => {
406
+ expect(setup.readList()).toStrictEqual(OPTIMISTIC_LIST);
407
+ });
408
+ unmount();
409
+ const response = await pending;
410
+
411
+ expect(response.status).toBe(400);
412
+ expect(setup.rollback).toHaveBeenCalledTimes(1);
413
+ expect(setup.rollback.mock.calls[0][0].reason).toBe("error");
414
+ expect(setup.readList()).toStrictEqual(INITIAL_LIST);
415
+ });
416
+
417
+ it("should invalidate after successful request", async () => {
418
+ const setup = createSetup();
419
+ mockRequest(setup.mutation, { data: { ok: true }, delay: 30 });
420
+ const { result, unmount } = renderHook(() => useSubmit(setup.mutation));
421
+
422
+ const pending = startSubmit(result.current.submit);
423
+ await waitFor(() => {
424
+ expect(setup.readList()).toStrictEqual(OPTIMISTIC_LIST);
425
+ });
426
+ unmount();
427
+ await pending;
428
+
429
+ expect(setup.rollback).not.toHaveBeenCalled();
430
+ expect(setup.invalidate).toHaveBeenCalledTimes(1);
431
+ expect(setup.invalidate).toHaveBeenCalledWith(setup.list);
432
+ });
433
+
434
+ it("should roll back aborted request", async () => {
435
+ const setup = createSetup();
436
+ mockRequest(setup.mutation, { delay: 100 });
437
+ const { result, unmount } = renderHook(() => useSubmit(setup.mutation));
438
+
439
+ const pending = startSubmit(result.current.submit);
440
+ await waitFor(() => {
441
+ expect(setup.dispatcher.getAllRunningRequests()).toHaveLength(1);
442
+ });
443
+ unmount();
444
+ setup.mutation.abort();
445
+ await pending;
446
+
447
+ expect(setup.rollback).toHaveBeenCalledTimes(1);
448
+ expect(setup.rollback.mock.calls[0][0].reason).toBe("abort");
449
+ expect(setup.readList()).toStrictEqual(INITIAL_LIST);
450
+ });
451
+
452
+ it("should roll back request removed from the queue", async () => {
453
+ const setup = createSetup();
454
+ setup.dispatcher.stop(setup.queryKey);
455
+ const { result, unmount } = renderHook(() => useSubmit(setup.mutation));
456
+ let requestId = "";
457
+
458
+ const pending = startSubmit(result.current.submit, {
459
+ onBeforeSent: (data: { requestId: string }) => {
460
+ requestId = data.requestId;
461
+ },
462
+ });
463
+ await waitFor(() => {
464
+ expect(requestId).not.toBe("");
465
+ });
466
+ unmount();
467
+ setup.dispatcher.delete(setup.queryKey, requestId, setup.abortKey);
468
+ await pending;
469
+
470
+ expect(setup.rollback).toHaveBeenCalledTimes(1);
471
+ expect(setup.rollback.mock.calls[0][0].reason).toBe("removed");
472
+ expect(setup.readList()).toStrictEqual(INITIAL_LIST);
473
+ });
474
+
475
+ it("should roll back once retries are exhausted", async () => {
476
+ const setup = createSetup();
477
+ const request = setup.mutation.setRetry(1).setRetryTime(10);
478
+ mockRequest(request, { status: 400 });
479
+ const { result, unmount } = renderHook(() => useSubmit(request));
480
+ const unmountListener = setup.client.requestManager.events.onResponse(() => {
481
+ unmountListener();
482
+ unmount();
483
+ mockRequest(request, { status: 500 });
484
+ });
485
+
486
+ await startSubmit(result.current.submit);
487
+
488
+ expect(setup.responses).toHaveLength(2);
489
+ expect(setup.rollback).toHaveBeenCalledTimes(1);
490
+ // Status of the last attempt proves the first failure did not trigger the rollback
491
+ expect(setup.rollback.mock.calls[0][0].response?.status).toBe(500);
492
+ expect(setup.readList()).toStrictEqual(INITIAL_LIST);
493
+ });
494
+ });
495
+
496
+ describe("when rendered in StrictMode", () => {
497
+ it("should roll back failed request once", async () => {
498
+ const setup = createSetup();
499
+ mockRequest(setup.mutation, { status: 400 });
500
+ const { result } = renderHook(() => useSubmit(setup.mutation), { wrapper: StrictMode });
501
+
502
+ await finishSubmit(startSubmit(result.current.submit));
503
+
504
+ expect(setup.rollback).toHaveBeenCalledTimes(1);
505
+ expect(setup.readList()).toStrictEqual(INITIAL_LIST);
506
+ });
507
+
508
+ it("should invalidate successful request once", async () => {
509
+ const setup = createSetup();
510
+ mockRequest(setup.mutation, { data: { ok: true } });
511
+ const { result } = renderHook(() => useSubmit(setup.mutation), { wrapper: StrictMode });
512
+
513
+ await finishSubmit(startSubmit(result.current.submit));
514
+
515
+ expect(setup.rollback).not.toHaveBeenCalled();
516
+ expect(setup.invalidate).toHaveBeenCalledTimes(1);
517
+ });
518
+
519
+ it("should roll back once when unmounted while pending", async () => {
520
+ const setup = createSetup();
521
+ mockRequest(setup.mutation, { status: 400, delay: 30 });
522
+ const { result, unmount } = renderHook(() => useSubmit(setup.mutation), { wrapper: StrictMode });
523
+
524
+ const pending = startSubmit(result.current.submit);
525
+ await waitFor(() => {
526
+ expect(setup.readList()).toStrictEqual(OPTIMISTIC_LIST);
527
+ });
528
+ unmount();
529
+ await pending;
530
+
531
+ expect(setup.rollback).toHaveBeenCalledTimes(1);
532
+ expect(setup.readList()).toStrictEqual(INITIAL_LIST);
533
+ });
534
+ });
535
+
536
+ describe("when multiple mutations are running", () => {
537
+ const createItemMutation = (setup: Setup, item: string) => {
538
+ const rollback = vi.fn(() => {
539
+ setup.removeItem(item);
540
+ });
541
+ const request = setup.client
542
+ .createRequest<{ response: null }>()({ endpoint: `/mutation/${item}`, method: "POST" })
543
+ .setOptimistic(() => {
544
+ setup.addItem(item);
545
+ return { rollback };
546
+ });
547
+ return { request, rollback };
548
+ };
549
+
550
+ it("should roll back only the failed mutation of two hooks", async () => {
551
+ const setup = createSetup();
552
+ const failed = createItemMutation(setup, "failed");
553
+ const passed = createItemMutation(setup, "passed");
554
+ mockRequest(failed.request, { status: 400, delay: 10 });
555
+ mockRequest(passed.request, { delay: 30 });
556
+ const failedHook = renderHook(() => useSubmit(failed.request));
557
+ const passedHook = renderHook(() => useSubmit(passed.request));
558
+
559
+ await finishSubmit(
560
+ Promise.all([startSubmit(failedHook.result.current.submit), startSubmit(passedHook.result.current.submit)]),
561
+ );
562
+
563
+ expect(failed.rollback).toHaveBeenCalledTimes(1);
564
+ expect(passed.rollback).not.toHaveBeenCalled();
565
+ expect(setup.readList()).toStrictEqual([SERVER_ITEM, "passed"]);
566
+ });
567
+
568
+ it("should roll back each of two failed mutations once", async () => {
569
+ const setup = createSetup();
570
+ const first = createItemMutation(setup, "first");
571
+ const second = createItemMutation(setup, "second");
572
+ mockRequest(first.request, { status: 400, delay: 30 });
573
+ mockRequest(second.request, { status: 500, delay: 10 });
574
+ const firstHook = renderHook(() => useSubmit(first.request));
575
+ const secondHook = renderHook(() => useSubmit(second.request));
576
+
577
+ await finishSubmit(
578
+ Promise.all([startSubmit(firstHook.result.current.submit), startSubmit(secondHook.result.current.submit)]),
579
+ );
580
+
581
+ expect(first.rollback).toHaveBeenCalledTimes(1);
582
+ expect(second.rollback).toHaveBeenCalledTimes(1);
583
+ expect(setup.readList()).toStrictEqual(INITIAL_LIST);
584
+ });
585
+
586
+ it("should roll back two submits of one hook separately", async () => {
587
+ const setup = createSetup();
588
+ const rollbacks: Record<string, ReturnType<typeof vi.fn>> = {};
589
+ const request = setup.client
590
+ .createRequest<{ response: null; payload: { item: string } }>()({ endpoint: "/mutation", method: "POST" })
591
+ .setOptimistic(({ payload }) => {
592
+ setup.addItem(payload.item);
593
+ const rollback = vi.fn(() => {
594
+ setup.removeItem(payload.item);
595
+ });
596
+ rollbacks[payload.item] = rollback;
597
+ return { rollback };
598
+ });
599
+ mockRequest(request, { status: 400, delay: 20 });
600
+ const { result } = renderHook(() => useSubmit(request));
601
+
602
+ await finishSubmit(
603
+ Promise.all([
604
+ startSubmit(result.current.submit, { payload: { item: "first" } }),
605
+ startSubmit(result.current.submit, { payload: { item: "second" } }),
606
+ ]),
607
+ );
608
+
609
+ expect(rollbacks.first).toHaveBeenCalledTimes(1);
610
+ expect(rollbacks.second).toHaveBeenCalledTimes(1);
611
+ expect(setup.readList()).toStrictEqual(INITIAL_LIST);
612
+ });
613
+
614
+ it("should roll back once when two hooks observe the same request", async () => {
615
+ const setup = createSetup();
616
+ mockRequest(setup.mutation, { status: 400 });
617
+ const submitting = renderHook(() => useSubmit(setup.mutation));
618
+ renderHook(() => useSubmit(setup.mutation));
619
+
620
+ await finishSubmit(startSubmit(submitting.result.current.submit));
621
+
622
+ expect(setup.rollback).toHaveBeenCalledTimes(1);
623
+ });
624
+ });
625
+ });