@hyper-fetch/core 9.6.2 → 9.8.0

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.
Files changed (55) hide show
  1. package/__tests__/features/adapter/adapter.typescript.spec.ts +34 -0
  2. package/__tests__/features/adapter/adapter.utils.spec.ts +10 -0
  3. package/__tests__/features/cache/cache.utils.spec.ts +18 -0
  4. package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
  5. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  6. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  7. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  8. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  9. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  10. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  11. package/__tests__/features/request/request.cloning.spec.ts +28 -0
  12. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  13. package/__tests__/features/request/request.sending.spec.ts +13 -10
  14. package/__tests__/type-stress/custom-adapter/custom-adapter.ts +20 -0
  15. package/__tests__/type-stress/custom-adapter/tsconfig.json +4 -0
  16. package/__tests__/utils/optimistic.utils.ts +124 -0
  17. package/dist/cache/cache.d.ts.map +1 -1
  18. package/dist/client/client.d.ts.map +1 -1
  19. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.mjs +578 -70
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/optimistic/index.d.ts +5 -0
  25. package/dist/optimistic/index.d.ts.map +1 -0
  26. package/dist/optimistic/optimistic.d.ts +67 -0
  27. package/dist/optimistic/optimistic.d.ts.map +1 -0
  28. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  29. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  30. package/dist/optimistic/optimistic.types.d.ts +109 -0
  31. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  32. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  33. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  34. package/dist/request/request.d.ts +13 -5
  35. package/dist/request/request.d.ts.map +1 -1
  36. package/dist/request/request.types.d.ts +40 -1
  37. package/dist/request/request.types.d.ts.map +1 -1
  38. package/dist/request/request.utils.d.ts.map +1 -1
  39. package/dist/types/adapter.types.d.ts +12 -1
  40. package/dist/types/adapter.types.d.ts.map +1 -1
  41. package/package.json +2 -2
  42. package/src/cache/cache.ts +2 -1
  43. package/src/client/client.ts +2 -0
  44. package/src/dispatcher/dispatcher.ts +13 -0
  45. package/src/index.ts +1 -0
  46. package/src/optimistic/index.ts +4 -0
  47. package/src/optimistic/optimistic.settlement.ts +406 -0
  48. package/src/optimistic/optimistic.ts +162 -0
  49. package/src/optimistic/optimistic.types.ts +175 -0
  50. package/src/optimistic/optimistic.utils.ts +112 -0
  51. package/src/request/request.ts +19 -6
  52. package/src/request/request.types.ts +41 -1
  53. package/src/request/request.utils.ts +30 -54
  54. package/src/types/adapter.types.ts +42 -25
  55. package/tsconfig.json +2 -0
@@ -0,0 +1,1001 @@
1
+ import { createHttpMockingServer } from "@hyper-fetch/testing";
2
+ import { waitFor } from "@testing-library/dom";
3
+
4
+ import type { CacheValueType } from "cache";
5
+ import { Client } from "client";
6
+ import { optimistic } from "optimistic";
7
+ import type { OptimisticOperationRollbackArgs } from "optimistic";
8
+ import type { RequestInstance } from "request";
9
+ import { scopeKey } from "request";
10
+ import type { Stats, Todo } from "../../utils/optimistic.utils";
11
+ import { getThrownErrors } from "../../utils/fixtures.utils";
12
+ import { createTodo, readCache, seedCache } from "../../utils/optimistic.utils";
13
+
14
+ const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
15
+
16
+ type SendResult = { success: boolean; status: number | null };
17
+
18
+ const INITIAL_TODOS = [createTodo(1), createTodo(2), createTodo(3)];
19
+
20
+ const createSetup = () => {
21
+ const client = new Client({ url: "shared-base-url" });
22
+ const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
23
+ const getStats = client.createRequest<{ response: Stats }>()({ endpoint: "/stats" });
24
+ // The same list with filters and pages in its query params
25
+ const listQuery = client.createRequest<{ response: Todo[]; queryParams: { done?: boolean; page?: number } }>()({
26
+ endpoint: "/todos",
27
+ });
28
+ const updateTodo = client.createRequest<{ response: Todo; payload: Partial<Todo> }>()({
29
+ endpoint: "/todos/:todoId",
30
+ method: "PATCH",
31
+ });
32
+ const createTodoRequest = client.createRequest<{ response: Todo; payload: Omit<Todo, "id"> }>()({
33
+ endpoint: "/todos",
34
+ method: "POST",
35
+ });
36
+
37
+ seedCache(client, getTodos, INITIAL_TODOS);
38
+ seedCache(client, getStats, { total: 3, done: 0 });
39
+
40
+ const invalidate = vi.spyOn(client.cache, "invalidate");
41
+ const logError = vi.spyOn(client.logger, "error");
42
+ const todos = () => readCache<Todo[]>(client, getTodos);
43
+ const stats = () => readCache<Stats>(client, getStats);
44
+ const wasRefreshed = (request: RequestInstance) => {
45
+ return invalidate.mock.calls.some(([target]) => {
46
+ return (
47
+ target instanceof Object &&
48
+ "cacheKey" in target &&
49
+ scopeKey(target.cacheKey, target.scope) === scopeKey(request.cacheKey, request.scope)
50
+ );
51
+ });
52
+ };
53
+
54
+ return { client, getTodos, getStats, listQuery, updateTodo, createTodoRequest, invalidate, logError, todos, stats, wasRefreshed };
55
+ };
56
+
57
+ type Setup = ReturnType<typeof createSetup>;
58
+
59
+ const countDataEvents = (setup: Setup, request: RequestInstance) => {
60
+ const events: unknown[] = [];
61
+ setup.client.cache.events.onDataByKey(request.cacheKey, (data: CacheValueType) => events.push(data.data));
62
+ return events;
63
+ };
64
+
65
+ describe("Optimistic [ Rollback and commit ]", () => {
66
+ beforeAll(() => {
67
+ startServer();
68
+ });
69
+
70
+ afterEach(() => {
71
+ resetMocks();
72
+ });
73
+
74
+ afterAll(() => {
75
+ stopServer();
76
+ });
77
+
78
+ describe("when the mutation fails", () => {
79
+ it("should call rollback with one object holding the current and previous data", async () => {
80
+ const setup = createSetup();
81
+ const rollback = vi.fn((_args: OptimisticOperationRollbackArgs<Todo[], RequestInstance>) => {});
82
+ let sentRequest: RequestInstance | undefined;
83
+ const request = setup.updateTodo.setParams({ todoId: 2 }).setOptimistic(({ params, payload }) => [
84
+ optimistic(setup.getTodos).patch(params.todoId, payload).rollback(rollback),
85
+ ]);
86
+ mockRequest(request, { status: 400, delay: 20 });
87
+
88
+ const pending = request.send({
89
+ payload: { done: true },
90
+ onBeforeSent: ({ request: sent }) => {
91
+ sentRequest = sent;
92
+ },
93
+ });
94
+ // Another change lands while the mutation is pending
95
+ setup.client.cache.update(setup.getTodos, (prev) => ({
96
+ data: [...(prev?.data ?? []), createTodo(4)],
97
+ }));
98
+ const response = await pending;
99
+
100
+ expect(response.success).toBeFalse();
101
+ expect(rollback).toHaveBeenCalledTimes(1);
102
+ const [args] = rollback.mock.calls[0];
103
+ expect(Object.keys(args).toSorted()).toStrictEqual(["data", "previous", "reason", "request", "response"]);
104
+ expect(args.previous).toStrictEqual(INITIAL_TODOS);
105
+ expect(args.data).toStrictEqual([INITIAL_TODOS[0], { ...INITIAL_TODOS[1], done: true }, INITIAL_TODOS[2], createTodo(4)]);
106
+ expect(args.reason).toBe("error");
107
+ expect(args.response?.status).toBe(400);
108
+ expect(args.response?.success).toBeFalse();
109
+ expect(args.request).toBe(sentRequest);
110
+ });
111
+
112
+ it("should write the returned data and keep changes made since", async () => {
113
+ const setup = createSetup();
114
+ const request = setup.updateTodo.setParams({ todoId: 2 }).setOptimistic(({ params }) => [
115
+ optimistic(setup.getTodos)
116
+ .patch(params.todoId, { done: true })
117
+ .rollback(({ data, previous }) => {
118
+ const before = previous.find((todo) => todo.id === params.todoId);
119
+ return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
120
+ }),
121
+ ]);
122
+ mockRequest(request, { status: 500, delay: 20 });
123
+
124
+ const pending = request.send({ payload: {} });
125
+ setup.client.cache.update(setup.getTodos, (prev) => ({
126
+ data: (prev?.data ?? []).map((todo) => (todo.id === 3 ? { ...todo, likes: 7 } : todo)),
127
+ }));
128
+ await pending;
129
+
130
+ expect(setup.todos()).toStrictEqual([INITIAL_TODOS[0], INITIAL_TODOS[1], { ...INITIAL_TODOS[2], likes: 7 }]);
131
+ });
132
+
133
+ it("should see the data of a server response that landed in the meantime", async () => {
134
+ const setup = createSetup();
135
+ const server = [createTodo(1, { title: "from server" })];
136
+ const rollback = vi.fn();
137
+ const request = setup.updateTodo
138
+ .setParams({ todoId: 1 })
139
+ .setOptimistic(() => [optimistic(setup.getTodos).remove(1).rollback(rollback)]);
140
+ mockRequest(request, { status: 500, delay: 20 });
141
+
142
+ const pending = request.send({ payload: {} });
143
+ seedCache(setup.client, setup.getTodos, server);
144
+ await pending;
145
+
146
+ expect(rollback).toHaveBeenCalledWith(expect.objectContaining({ data: server, previous: INITIAL_TODOS }));
147
+ });
148
+
149
+ it("should leave the data untouched when rollback returns nothing and still count it as run", async () => {
150
+ const setup = createSetup();
151
+ const events = countDataEvents(setup, setup.getTodos);
152
+ const rollback = vi.fn();
153
+ const request = setup.updateTodo
154
+ .setParams({ todoId: 1 })
155
+ .setOptimistic(() => [optimistic(setup.getTodos).remove(1).rollback(rollback)]);
156
+ mockRequest(request, { status: 500 });
157
+
158
+ await request.send({ payload: {} });
159
+
160
+ expect(rollback).toHaveBeenCalledTimes(1);
161
+ expect(setup.todos()).toStrictEqual([INITIAL_TODOS[1], INITIAL_TODOS[2]]);
162
+ // Only the optimistic change produced an event
163
+ expect(events).toHaveLength(1);
164
+ expect(setup.wasRefreshed(setup.getTodos)).toBeTrue();
165
+ });
166
+
167
+ it("should not write when rollback returns the current data", async () => {
168
+ const setup = createSetup();
169
+ const events = countDataEvents(setup, setup.getTodos);
170
+ const request = setup.updateTodo
171
+ .setParams({ todoId: 1 })
172
+ .setOptimistic(() => [optimistic(setup.getTodos).remove(1).rollback(({ data }) => data)]);
173
+ mockRequest(request, { status: 500 });
174
+
175
+ await request.send({ payload: {} });
176
+
177
+ expect(events).toHaveLength(1);
178
+ });
179
+
180
+ it("should run the rollbacks in reverse order and skip operations without one", async () => {
181
+ const setup = createSetup();
182
+ const order: string[] = [];
183
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => [
184
+ optimistic(setup.getTodos)
185
+ .patch(1, { done: true })
186
+ .rollback(({ data }) => {
187
+ order.push("first");
188
+ return data.map((todo) => (todo.id === 1 ? { ...todo, done: false } : todo));
189
+ }),
190
+ optimistic(setup.getStats).increment("done", 1),
191
+ optimistic(setup.getStats)
192
+ .increment("total", 1)
193
+ .rollback(({ data }) => {
194
+ order.push("third");
195
+ return { ...data, total: data.total - 1 };
196
+ }),
197
+ ]);
198
+ mockRequest(request, { status: 500 });
199
+
200
+ await request.send({ payload: {} });
201
+
202
+ expect(order).toStrictEqual(["third", "first"]);
203
+ expect(setup.todos()).toStrictEqual(INITIAL_TODOS);
204
+ // The operation without rollback stays until the refresh replaces it
205
+ expect(setup.stats()).toStrictEqual({ total: 3, done: 1 });
206
+ expect(setup.wasRefreshed(setup.getStats)).toBeTrue();
207
+ expect(setup.wasRefreshed(setup.getTodos)).toBeTrue();
208
+ });
209
+
210
+ it("should only refresh when no operation has a rollback", async () => {
211
+ const setup = createSetup();
212
+ const request = setup.updateTodo
213
+ .setParams({ todoId: 1 })
214
+ .setOptimistic(() => [optimistic(setup.getTodos).patch(1, { done: true })]);
215
+ mockRequest(request, { status: 500 });
216
+
217
+ await request.send({ payload: {} });
218
+
219
+ expect(setup.todos()?.[0].done).toBeTrue();
220
+ expect(setup.invalidate).toHaveBeenCalledTimes(1);
221
+ expect(setup.wasRefreshed(setup.getTodos)).toBeTrue();
222
+ expect(setup.client.cache.get(setup.getTodos.cacheKey)?.staleTime).toBe(0);
223
+ });
224
+
225
+ it("should mark a failed item instead of removing it", async () => {
226
+ const setup = createSetup();
227
+ type Message = { id: string; text: string; status: "sending" | "failed" | "sent" };
228
+ const getMessages = setup.client.createRequest<{ response: Message[] }>()({ endpoint: "/messages" });
229
+ seedCache(setup.client, getMessages, []);
230
+ const message: Message = { id: "temp", text: "Hi", status: "sending" };
231
+ const send = setup.client
232
+ .createRequest<{ response: Message; payload: Message }>()({ endpoint: "/messages", method: "POST" })
233
+ .setOptimistic(({ payload }) => [
234
+ optimistic(getMessages)
235
+ .insert(payload)
236
+ .rollback(({ data, reason }) =>
237
+ reason === "error"
238
+ ? data.map((item) => (item.id === payload.id ? { ...item, status: "failed" as const } : item))
239
+ : data.filter((item) => item.id !== payload.id),
240
+ ),
241
+ ]);
242
+ mockRequest(send, { status: 500 });
243
+
244
+ await send.send({ payload: message });
245
+
246
+ expect(readCache(setup.client, getMessages)).toStrictEqual([{ ...message, status: "failed" }]);
247
+ });
248
+ });
249
+
250
+ describe("when the mutation is aborted or removed", () => {
251
+ it("should roll back with the abort reason and response", async () => {
252
+ const setup = createSetup();
253
+ const rollback = vi.fn(({ previous }: { previous: Todo[] }) => previous);
254
+ const request = setup.updateTodo
255
+ .setParams({ todoId: 1 })
256
+ .setOptimistic(() => [optimistic(setup.getTodos).remove(1).rollback(rollback)]);
257
+ mockRequest(request, { delay: 100 });
258
+
259
+ await request.send({
260
+ payload: {},
261
+ onRequestStart: () => {
262
+ request.abort();
263
+ },
264
+ });
265
+
266
+ expect(rollback).toHaveBeenCalledTimes(1);
267
+ expect(rollback).toHaveBeenCalledWith(expect.objectContaining({ reason: "abort" }));
268
+ expect(rollback.mock.calls[0][0]).toHaveProperty("response.success", false);
269
+ expect(setup.todos()).toStrictEqual(INITIAL_TODOS);
270
+ });
271
+
272
+ it("should roll back without response when removed from the queue", async () => {
273
+ const setup = createSetup();
274
+ const rollback = vi.fn(({ data }: { data: Todo[] }) => [createTodo(1), ...data]);
275
+ const request = setup.updateTodo
276
+ .setParams({ todoId: 1 })
277
+ .setOptimistic(() => [optimistic(setup.getTodos).remove(1).rollback(rollback)]);
278
+ mockRequest(request);
279
+ const queryKey = scopeKey(request.queryKey, request.scope);
280
+ setup.client.submitDispatcher.stop(queryKey);
281
+
282
+ const response = await request.send({
283
+ payload: {},
284
+ onBeforeSent: ({ requestId }) => {
285
+ queueMicrotask(() => {
286
+ setup.client.submitDispatcher.delete(queryKey, requestId, scopeKey(request.abortKey, request.scope));
287
+ });
288
+ },
289
+ });
290
+
291
+ expect(response.success).toBeFalse();
292
+ expect(rollback).toHaveBeenCalledTimes(1);
293
+ const [args] = rollback.mock.calls[0];
294
+ expect(args).toHaveProperty("reason", "removed");
295
+ expect(args).not.toHaveProperty("response");
296
+ expect(setup.todos()).toStrictEqual([createTodo(1), INITIAL_TODOS[1], INITIAL_TODOS[2]]);
297
+ expect(setup.wasRefreshed(setup.getTodos)).toBeTrue();
298
+ });
299
+ });
300
+
301
+ describe("when the mutation succeeds", () => {
302
+ it("should not roll back and keep the optimistic value until the refresh", async () => {
303
+ const setup = createSetup();
304
+ const rollback = vi.fn();
305
+ const request = setup.updateTodo
306
+ .setParams({ todoId: 1 })
307
+ .setOptimistic(() => [optimistic(setup.getTodos).patch(1, { done: true }).rollback(rollback)]);
308
+ mockRequest(request, { data: createTodo(1, { done: true }) });
309
+
310
+ const response = await request.send({ payload: { done: true } });
311
+
312
+ expect(response.success).toBeTrue();
313
+ expect(rollback).not.toHaveBeenCalled();
314
+ expect(setup.todos()?.[0].done).toBeTrue();
315
+ expect(setup.wasRefreshed(setup.getTodos)).toBeTrue();
316
+ });
317
+
318
+ it("should swap the temporary item for the server one in commit", async () => {
319
+ const setup = createSetup();
320
+ const commit = vi.fn();
321
+ const request = setup.createTodoRequest.setOptimistic(({ payload, optimistic: typedOptimistic }) => {
322
+ const temp = { id: -1, ...payload };
323
+ return [
324
+ typedOptimistic(setup.getTodos)
325
+ .insert(temp)
326
+ .commit((args) => {
327
+ commit(args);
328
+ return args.data.map((todo) => (todo.id === temp.id ? args.response.data : todo));
329
+ })
330
+ .rollback(({ data }) => data.filter((todo) => todo.id !== temp.id)),
331
+ ];
332
+ });
333
+ mockRequest(request, { data: createTodo(10, { title: "new" }) });
334
+ let sentRequest: RequestInstance | undefined;
335
+
336
+ await request.send({
337
+ payload: { title: "new", done: false, likes: 0 },
338
+ onBeforeSent: ({ request: sent }) => {
339
+ sentRequest = sent;
340
+ },
341
+ });
342
+
343
+ expect(setup.todos()).toStrictEqual([...INITIAL_TODOS, createTodo(10, { title: "new" })]);
344
+ expect(commit).toHaveBeenCalledTimes(1);
345
+ const [args] = commit.mock.calls[0];
346
+ expect(Object.keys(args).toSorted()).toStrictEqual(["data", "request", "response"]);
347
+ expect(args.data).toStrictEqual([...INITIAL_TODOS, { id: -1, title: "new", done: false, likes: 0 }]);
348
+ expect(args.response.success).toBeTrue();
349
+ expect(args.request).toBe(sentRequest);
350
+ });
351
+
352
+ it("should keep the data when commit returns nothing", async () => {
353
+ const setup = createSetup();
354
+ const events = countDataEvents(setup, setup.getTodos);
355
+ const request = setup.updateTodo
356
+ .setParams({ todoId: 1 })
357
+ .setOptimistic(() => [optimistic(setup.getTodos).remove(1).commit(() => {})]);
358
+ mockRequest(request, { data: createTodo(1) });
359
+
360
+ await request.send({ payload: {} });
361
+
362
+ expect(events).toHaveLength(1);
363
+ expect(setup.todos()).toStrictEqual([INITIAL_TODOS[1], INITIAL_TODOS[2]]);
364
+ });
365
+ });
366
+
367
+ describe("when user code fails", () => {
368
+ it("should contain a throwing helper, apply the others and refresh the target", async () => {
369
+ const setup = createSetup();
370
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => [
371
+ optimistic(setup.getTodos).set(() => {
372
+ throw new Error("Helper failed");
373
+ }),
374
+ optimistic(setup.getStats).increment("total", 1),
375
+ ]);
376
+ mockRequest(request, { data: createTodo(1) });
377
+
378
+ let response: SendResult | undefined;
379
+ const thrown = await getThrownErrors(async () => {
380
+ response = await request.send({ payload: {} });
381
+ });
382
+
383
+ expect(response?.success).toBeTrue();
384
+ expect(thrown).toStrictEqual([new Error("Helper failed")]);
385
+ expect(setup.todos()).toStrictEqual(INITIAL_TODOS);
386
+ expect(setup.stats()?.total).toBe(4);
387
+ expect(setup.logError).toHaveBeenCalledWith(expect.objectContaining({ title: "Optimistic update failed" }));
388
+ expect(setup.wasRefreshed(setup.getTodos)).toBeTrue();
389
+ });
390
+
391
+ it("should refresh a target whose helper threw even when nothing else refreshes", async () => {
392
+ const setup = createSetup();
393
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => ({
394
+ updates: [optimistic(setup.getTodos).patch(1, { done: true }), optimistic(setup.getStats).list("total" as never).remove(() => true)],
395
+ revalidate: false,
396
+ }));
397
+ mockRequest(request, { data: createTodo(1) });
398
+
399
+ const thrown = await getThrownErrors(() => request.send({ payload: {} }));
400
+
401
+ expect(thrown).toStrictEqual([expect.any(TypeError)]);
402
+ expect(setup.wasRefreshed(setup.getStats)).toBeTrue();
403
+ expect(setup.wasRefreshed(setup.getTodos)).toBeFalse();
404
+ });
405
+
406
+ it("should contain values which are not operations", async () => {
407
+ const setup = createSetup();
408
+ const request = setup.updateTodo
409
+ .setParams({ todoId: 1 })
410
+ .setOptimistic(() => ({ updates: [{ fake: true } as never, optimistic(setup.getStats).increment("total", 1)] }));
411
+ mockRequest(request, { data: createTodo(1) });
412
+
413
+ let response: SendResult | undefined;
414
+ const thrown = await getThrownErrors(async () => {
415
+ response = await request.send({ payload: {} });
416
+ });
417
+
418
+ expect(response?.success).toBeTrue();
419
+ expect(thrown).toStrictEqual([expect.any(TypeError)]);
420
+ expect(setup.stats()?.total).toBe(4);
421
+ expect(setup.logError).toHaveBeenCalledWith(expect.objectContaining({ title: "Optimistic update failed" }));
422
+ });
423
+
424
+ it("should contain a throwing rollback, run the others and refresh", async () => {
425
+ const setup = createSetup();
426
+ const objectRollback = vi.fn();
427
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => ({
428
+ updates: [
429
+ optimistic(setup.getTodos)
430
+ .remove(1)
431
+ .rollback(({ previous }) => previous),
432
+ optimistic(setup.getStats)
433
+ .increment("total", -1)
434
+ .rollback(() => {
435
+ throw new Error("Rollback failed");
436
+ }),
437
+ ],
438
+ rollback: objectRollback,
439
+ revalidate: false,
440
+ }));
441
+ mockRequest(request, { status: 500 });
442
+
443
+ let response: SendResult | undefined;
444
+ const thrown = await getThrownErrors(async () => {
445
+ response = await request.send({ payload: {} });
446
+ });
447
+
448
+ expect(response?.status).toBe(500);
449
+ expect(thrown).toStrictEqual([new Error("Rollback failed")]);
450
+ expect(setup.todos()).toStrictEqual(INITIAL_TODOS);
451
+ expect(objectRollback).toHaveBeenCalledTimes(1);
452
+ expect(setup.logError).toHaveBeenCalledWith(expect.objectContaining({ title: "Optimistic rollback failed" }));
453
+ expect(setup.wasRefreshed(setup.getStats)).toBeTrue();
454
+ expect(setup.wasRefreshed(setup.getTodos)).toBeFalse();
455
+ });
456
+
457
+ it("should report a rollback returning a promise and ignore its value", async () => {
458
+ const setup = createSetup();
459
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => [
460
+ optimistic(setup.getTodos)
461
+ .remove(1)
462
+ .rollback((async () => INITIAL_TODOS) as never),
463
+ ]);
464
+ mockRequest(request, { status: 500 });
465
+
466
+ const thrown = await getThrownErrors(() => request.send({ payload: {} }));
467
+
468
+ expect(thrown).toStrictEqual([expect.any(TypeError)]);
469
+ expect(setup.todos()).toStrictEqual([INITIAL_TODOS[1], INITIAL_TODOS[2]]);
470
+ expect(setup.logError).toHaveBeenCalledWith(expect.objectContaining({ title: "Optimistic rollback failed" }));
471
+ expect(setup.wasRefreshed(setup.getTodos)).toBeTrue();
472
+ });
473
+
474
+ it("should report a rejected rollback promise", async () => {
475
+ const setup = createSetup();
476
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => [
477
+ optimistic(setup.getTodos)
478
+ .remove(1)
479
+ .rollback((() => Promise.reject(new Error("Async failed"))) as never),
480
+ ]);
481
+ mockRequest(request, { status: 500 });
482
+
483
+ const thrown = await getThrownErrors(async () => {
484
+ await request.send({ payload: {} });
485
+ await waitFor(() => {
486
+ expect(setup.logError).toHaveBeenCalledWith(
487
+ expect.objectContaining({ extra: expect.objectContaining({ error: new Error("Async failed") }) }),
488
+ );
489
+ });
490
+ });
491
+
492
+ expect(thrown).toStrictEqual([expect.any(TypeError), new Error("Async failed")]);
493
+ });
494
+
495
+ it("should contain a throwing commit and refresh", async () => {
496
+ const setup = createSetup();
497
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => ({
498
+ updates: [
499
+ optimistic(setup.getTodos)
500
+ .patch(1, { done: true })
501
+ .commit(() => {
502
+ throw new Error("Commit failed");
503
+ }),
504
+ ],
505
+ revalidate: false,
506
+ }));
507
+ mockRequest(request, { data: createTodo(1) });
508
+
509
+ let response: SendResult | undefined;
510
+ const thrown = await getThrownErrors(async () => {
511
+ response = await request.send({ payload: {} });
512
+ });
513
+
514
+ expect(response?.success).toBeTrue();
515
+ expect(thrown).toStrictEqual([new Error("Commit failed")]);
516
+ expect(setup.logError).toHaveBeenCalledWith(expect.objectContaining({ title: "Optimistic commit failed" }));
517
+ expect(setup.wasRefreshed(setup.getTodos)).toBeTrue();
518
+ });
519
+ });
520
+
521
+ describe("when the target has no data", () => {
522
+ it("should skip the change and rollback, but refresh the target", async () => {
523
+ const setup = createSetup();
524
+ const getUsers = setup.client.createRequest<{ response: { id: number }[] }>()({ endpoint: "/users" });
525
+ const rollback = vi.fn();
526
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => [
527
+ optimistic(getUsers).insert({ id: 1 }).rollback(rollback),
528
+ optimistic(setup.getTodos)
529
+ .remove(1)
530
+ .rollback(({ previous }) => previous),
531
+ ]);
532
+ mockRequest(request, { status: 500 });
533
+
534
+ await request.send({ payload: {} });
535
+
536
+ expect(readCache(setup.client, getUsers)).toBeUndefined();
537
+ expect(rollback).not.toHaveBeenCalled();
538
+ expect(setup.logError).not.toHaveBeenCalled();
539
+ expect(setup.todos()).toStrictEqual(INITIAL_TODOS);
540
+ expect(setup.wasRefreshed(getUsers)).toBeTrue();
541
+ });
542
+
543
+ it("should not call rollback when the entry was deleted in the meantime", async () => {
544
+ const setup = createSetup();
545
+ const rollback = vi.fn(({ previous }: { previous: Todo[] }) => previous);
546
+ const request = setup.updateTodo
547
+ .setParams({ todoId: 1 })
548
+ .setOptimistic(() => [optimistic(setup.getTodos).remove(1).rollback(rollback)]);
549
+ mockRequest(request, { status: 500, delay: 20 });
550
+
551
+ const pending = request.send({ payload: {} });
552
+ setup.client.cache.delete(setup.getTodos.cacheKey);
553
+ await pending;
554
+
555
+ expect(rollback).not.toHaveBeenCalled();
556
+ expect(setup.logError).not.toHaveBeenCalled();
557
+ expect(setup.todos()).toBeUndefined();
558
+ });
559
+
560
+ it("should not call rollback when the cache was cleared in the meantime", async () => {
561
+ const setup = createSetup();
562
+ const rollback = vi.fn(({ previous }: { previous: Todo[] }) => previous);
563
+ const request = setup.updateTodo
564
+ .setParams({ todoId: 1 })
565
+ .setOptimistic(() => [optimistic(setup.getTodos).remove(1).rollback(rollback)]);
566
+ mockRequest(request, { status: 500, delay: 20 });
567
+
568
+ const pending = request.send({ payload: {} });
569
+ await setup.client.cache.clear();
570
+ await pending;
571
+
572
+ expect(rollback).not.toHaveBeenCalled();
573
+ expect(setup.logError).not.toHaveBeenCalled();
574
+ expect(setup.todos()).toBeUndefined();
575
+ });
576
+ });
577
+
578
+ describe("when combining helpers with the object form", () => {
579
+ it("should run the helper rollbacks before the object rollback and deliver the context", async () => {
580
+ const setup = createSetup();
581
+ const order: string[] = [];
582
+ const objectRollback = vi.fn((args: { reason: string }) => {
583
+ order.push(`object:${args.reason}`);
584
+ });
585
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => ({
586
+ context: { todoId: 1 },
587
+ updates: [
588
+ optimistic(setup.getTodos)
589
+ .remove(1)
590
+ .rollback(({ previous }) => {
591
+ order.push("helper");
592
+ return previous;
593
+ }),
594
+ ],
595
+ rollback: objectRollback,
596
+ invalidate: [setup.getStats],
597
+ }));
598
+ mockRequest(request, { status: 500 });
599
+ const onResponse = vi.fn();
600
+
601
+ await request.send({ payload: {}, onResponse });
602
+
603
+ expect(order).toStrictEqual(["helper", "object:error"]);
604
+ expect(onResponse).toHaveBeenCalledWith(
605
+ expect.objectContaining({ mutationContext: expect.objectContaining({ context: { todoId: 1 } }) }),
606
+ );
607
+ expect(setup.wasRefreshed(setup.getStats)).toBeFalse();
608
+ });
609
+
610
+ it("should run the object invalidation next to the commits on success", async () => {
611
+ const setup = createSetup();
612
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => ({
613
+ updates: [optimistic(setup.getTodos).patch(1, { done: true })],
614
+ invalidate: [setup.getStats],
615
+ }));
616
+ mockRequest(request, { data: createTodo(1) });
617
+
618
+ await request.send({ payload: {} });
619
+
620
+ expect(setup.wasRefreshed(setup.getStats)).toBeTrue();
621
+ expect(setup.wasRefreshed(setup.getTodos)).toBeTrue();
622
+ });
623
+
624
+ it("should pass the reason, response and request to a hand-written rollback", async () => {
625
+ const setup = createSetup();
626
+ const rollback = vi.fn();
627
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => ({ rollback }));
628
+ mockRequest(request, { status: 400 });
629
+
630
+ await request.send({ payload: {} });
631
+
632
+ expect(rollback).toHaveBeenCalledWith(
633
+ expect.objectContaining({ reason: "error", response: expect.objectContaining({ status: 400 }) }),
634
+ );
635
+ });
636
+ });
637
+
638
+ describe("when using rollbackOnError", () => {
639
+ const sendFailing = async (
640
+ setup: Setup,
641
+ rollbackOnError: boolean | ((args: { response: { status: number | null } }) => boolean),
642
+ status: 400 | 500 = 500,
643
+ ) => {
644
+ const rollback = vi.fn(({ previous }: { previous: Todo[] }) => previous);
645
+ const objectRollback = vi.fn();
646
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => ({
647
+ updates: [optimistic(setup.getTodos).remove(1).rollback(rollback)],
648
+ rollback: objectRollback,
649
+ rollbackOnError,
650
+ }));
651
+ mockRequest(request, { status });
652
+ await request.send({ payload: {} });
653
+ return { rollback, objectRollback };
654
+ };
655
+
656
+ it("should roll back with true", async () => {
657
+ const setup = createSetup();
658
+ const { rollback, objectRollback } = await sendFailing(setup, true);
659
+
660
+ expect(rollback).toHaveBeenCalledTimes(1);
661
+ expect(objectRollback).toHaveBeenCalledTimes(1);
662
+ expect(setup.todos()).toStrictEqual(INITIAL_TODOS);
663
+ });
664
+
665
+ it("should keep the change and not refresh with false", async () => {
666
+ const setup = createSetup();
667
+ const { rollback, objectRollback } = await sendFailing(setup, false);
668
+
669
+ expect(rollback).not.toHaveBeenCalled();
670
+ expect(objectRollback).not.toHaveBeenCalled();
671
+ expect(setup.todos()).toStrictEqual([INITIAL_TODOS[1], INITIAL_TODOS[2]]);
672
+ expect(setup.invalidate).not.toHaveBeenCalled();
673
+ });
674
+
675
+ it("should ask the predicate with the response and request", async () => {
676
+ const setup = createSetup();
677
+ const predicate = vi.fn(({ response }: { response: { status: number | null } }) => response.status !== 400);
678
+
679
+ const conflict = await sendFailing(setup, predicate, 400);
680
+ const serverError = await sendFailing(createSetup(), predicate, 500);
681
+
682
+ expect(predicate).toHaveBeenCalledTimes(2);
683
+ expect(predicate.mock.calls[0][0]).toHaveProperty("request");
684
+ expect(conflict.rollback).not.toHaveBeenCalled();
685
+ expect(serverError.rollback).toHaveBeenCalledTimes(1);
686
+ });
687
+
688
+ it("should roll back and report when the predicate throws", async () => {
689
+ const setup = createSetup();
690
+ let rollback: ReturnType<typeof vi.fn> | undefined;
691
+ const thrown = await getThrownErrors(async () => {
692
+ ({ rollback } = await sendFailing(setup, () => {
693
+ throw new Error("Predicate failed");
694
+ }));
695
+ });
696
+
697
+ expect(thrown).toStrictEqual([new Error("Predicate failed")]);
698
+ expect(rollback).toHaveBeenCalledTimes(1);
699
+ expect(setup.logError).toHaveBeenCalledWith(
700
+ expect.objectContaining({ title: "Optimistic rollbackOnError failed" }),
701
+ );
702
+ });
703
+
704
+ it("should still roll back an aborted request with false", async () => {
705
+ const setup = createSetup();
706
+ const rollback = vi.fn(({ previous }: { previous: Todo[] }) => previous);
707
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => ({
708
+ updates: [optimistic(setup.getTodos).remove(1).rollback(rollback)],
709
+ rollbackOnError: false,
710
+ }));
711
+ mockRequest(request, { delay: 100 });
712
+
713
+ await request.send({ payload: {}, onRequestStart: () => request.abort() });
714
+
715
+ expect(rollback).toHaveBeenCalledTimes(1);
716
+ expect(setup.todos()).toStrictEqual(INITIAL_TODOS);
717
+ });
718
+ });
719
+
720
+ describe("when using revalidate", () => {
721
+ it("should not refresh with false", async () => {
722
+ const setup = createSetup();
723
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => ({
724
+ updates: [optimistic(setup.getTodos).patch(1, { done: true })],
725
+ revalidate: false,
726
+ }));
727
+ mockRequest(request, { data: createTodo(1) });
728
+
729
+ await request.send({ payload: {} });
730
+
731
+ expect(setup.invalidate).not.toHaveBeenCalled();
732
+ expect(setup.todos()?.[0].done).toBeTrue();
733
+ });
734
+
735
+ it("should not refresh a failed mutation with false", async () => {
736
+ const setup = createSetup();
737
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => ({
738
+ updates: [optimistic(setup.getTodos).patch(1, { done: true })],
739
+ revalidate: false,
740
+ }));
741
+ mockRequest(request, { status: 500 });
742
+
743
+ await request.send({ payload: {} });
744
+
745
+ expect(setup.invalidate).not.toHaveBeenCalled();
746
+ });
747
+ });
748
+
749
+ describe("when passing optimistic per call", () => {
750
+ it("should use the operations instead of the request's callback", async () => {
751
+ const setup = createSetup();
752
+ const requestCallback = vi.fn(() => [optimistic(setup.getTodos).remove(1)]);
753
+ const request = setup.updateTodo.setParams({ todoId: 2 }).setOptimistic(requestCallback);
754
+ mockRequest(request, { data: createTodo(2), delay: 20 });
755
+
756
+ const pending = request.send({
757
+ payload: { done: true },
758
+ optimistic: [optimistic(setup.getTodos).patch(2, { done: true })],
759
+ });
760
+
761
+ expect(requestCallback).not.toHaveBeenCalled();
762
+ expect(setup.todos()?.map((todo) => todo.done)).toStrictEqual([false, true, false]);
763
+ await pending;
764
+ });
765
+
766
+ it("should call a per-call callback with the mutation's values", async () => {
767
+ const setup = createSetup();
768
+ const callback = vi.fn(() => [optimistic(setup.getTodos).remove(3)]);
769
+ const updateWithQuery = setup.client.createRequest<{
770
+ response: Todo;
771
+ payload: Partial<Todo>;
772
+ queryParams: string;
773
+ }>()({ endpoint: "/todos/:todoId", method: "PATCH" });
774
+ mockRequest(updateWithQuery, { data: createTodo(3) });
775
+
776
+ await updateWithQuery.send({
777
+ params: { todoId: 3 },
778
+ payload: { title: "x" },
779
+ queryParams: "?force=true",
780
+ optimistic: callback,
781
+ });
782
+
783
+ expect(callback).toHaveBeenCalledTimes(1);
784
+ expect(callback).toHaveBeenCalledWith(
785
+ expect.objectContaining({
786
+ params: { todoId: 3 },
787
+ payload: { title: "x" },
788
+ queryParams: "?force=true",
789
+ optimistic,
790
+ client: setup.client,
791
+ }),
792
+ );
793
+ expect(setup.todos()).toStrictEqual([INITIAL_TODOS[0], INITIAL_TODOS[1]]);
794
+ });
795
+
796
+ it("should not leak the option into the request configuration", async () => {
797
+ const setup = createSetup();
798
+ mockRequest(setup.updateTodo, { data: createTodo(1) });
799
+ let sentRequest: RequestInstance | undefined;
800
+
801
+ await setup.updateTodo.send({
802
+ params: { todoId: 1 },
803
+ payload: {},
804
+ optimistic: [],
805
+ onBeforeSent: ({ request }) => {
806
+ sentRequest = request;
807
+ },
808
+ });
809
+
810
+ expect(sentRequest?.toJSON()).not.toHaveProperty("optimistic");
811
+ expect(sentRequest?.optimistic).toBeUndefined();
812
+ });
813
+ });
814
+
815
+ describe("when targeting all variants", () => {
816
+ it("should change every query param variant and leave other endpoints alone", async () => {
817
+ const setup = createSetup();
818
+ const filtered = setup.listQuery.setQueryParams({ done: false });
819
+ const page = setup.listQuery.setQueryParams({ page: 2 });
820
+ const getTodo = setup.client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos/:todoId" });
821
+ const other = getTodo.setParams({ todoId: 1 });
822
+ const lookalike = setup.client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos-archive" });
823
+ seedCache(setup.client, filtered, INITIAL_TODOS);
824
+ seedCache(setup.client, page, [createTodo(4)]);
825
+ seedCache(setup.client, other, INITIAL_TODOS);
826
+ seedCache(setup.client, lookalike, INITIAL_TODOS);
827
+ const targetJson = setup.getTodos.toJSON();
828
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => [
829
+ optimistic
830
+ .all(setup.getTodos)
831
+ .remove(1)
832
+ .rollback(({ data, previous }) => {
833
+ const removed = previous.find((todo) => todo.id === 1);
834
+ return removed ? [removed, ...data] : data;
835
+ }),
836
+ ]);
837
+ mockRequest(request, { status: 500, delay: 20 });
838
+
839
+ const pending = request.send({ payload: {} });
840
+
841
+ expect(setup.todos()).toStrictEqual([INITIAL_TODOS[1], INITIAL_TODOS[2]]);
842
+ expect(readCache(setup.client, filtered)).toStrictEqual([INITIAL_TODOS[1], INITIAL_TODOS[2]]);
843
+ expect(readCache(setup.client, page)).toStrictEqual([createTodo(4)]);
844
+ expect(readCache(setup.client, other)).toStrictEqual(INITIAL_TODOS);
845
+ expect(readCache(setup.client, lookalike)).toStrictEqual(INITIAL_TODOS);
846
+
847
+ await pending;
848
+
849
+ // The target request itself is never changed
850
+ expect(setup.getTodos.toJSON()).toStrictEqual(targetJson);
851
+ expect(setup.todos()).toStrictEqual(INITIAL_TODOS);
852
+ expect(readCache(setup.client, filtered)).toStrictEqual(INITIAL_TODOS);
853
+ expect(readCache(setup.client, page)).toStrictEqual([createTodo(4)]);
854
+ expect(setup.wasRefreshed(filtered)).toBeTrue();
855
+ expect(setup.wasRefreshed(page)).toBeTrue();
856
+ expect(setup.wasRefreshed(other)).toBeFalse();
857
+ });
858
+
859
+ it("should match the variants of a request with query params set", async () => {
860
+ const setup = createSetup();
861
+ const filtered = setup.listQuery.setQueryParams({ done: true });
862
+ seedCache(setup.client, filtered, INITIAL_TODOS);
863
+ mockRequest(setup.updateTodo, { data: createTodo(1) });
864
+
865
+ await setup.updateTodo.send({
866
+ params: { todoId: 1 },
867
+ payload: {},
868
+ optimistic: [optimistic.all(filtered).remove(1)],
869
+ });
870
+
871
+ expect(setup.todos()).toHaveLength(2);
872
+ expect(readCache(setup.client, filtered)).toHaveLength(2);
873
+ });
874
+
875
+ it("should match pages derived from a custom cache key", async () => {
876
+ const setup = createSetup();
877
+ const feed = setup.getTodos.setCacheKey("feed");
878
+ const secondPage = feed.setCacheKey("feed_2");
879
+ const otherFeed = feed.setCacheKey("feedback");
880
+ seedCache(setup.client, feed, INITIAL_TODOS);
881
+ seedCache(setup.client, secondPage, [createTodo(1, { title: "page 2" })]);
882
+ seedCache(setup.client, otherFeed, INITIAL_TODOS);
883
+ mockRequest(setup.updateTodo, { data: createTodo(1) });
884
+
885
+ await setup.updateTodo.send({
886
+ params: { todoId: 1 },
887
+ payload: {},
888
+ optimistic: [optimistic.all(feed).patch(1, { done: true })],
889
+ });
890
+
891
+ expect(readCache<Todo[]>(setup.client, feed)?.[0].done).toBeTrue();
892
+ expect(readCache<Todo[]>(setup.client, secondPage)?.[0].done).toBeTrue();
893
+ expect(readCache<Todo[]>(setup.client, otherFeed)?.[0].done).toBeFalse();
894
+ });
895
+ });
896
+
897
+ describe("when using scopes and several clients", () => {
898
+ it("should only change the entry of the target's scope", async () => {
899
+ const setup = createSetup();
900
+ const scoped = setup.getTodos.setScope("user-1");
901
+ const otherScope = setup.getTodos.setScope("user-2");
902
+ seedCache(setup.client, scoped, INITIAL_TODOS);
903
+ seedCache(setup.client, otherScope, INITIAL_TODOS);
904
+ mockRequest(setup.updateTodo, { status: 500 });
905
+
906
+ const pending = setup.updateTodo.send({
907
+ params: { todoId: 1 },
908
+ payload: {},
909
+ optimistic: [
910
+ optimistic
911
+ .all(scoped)
912
+ .remove(1)
913
+ .rollback(({ previous }) => previous),
914
+ ],
915
+ });
916
+
917
+ expect(readCache(setup.client, scoped)).toHaveLength(2);
918
+ expect(readCache(setup.client, otherScope)).toStrictEqual(INITIAL_TODOS);
919
+ expect(setup.todos()).toStrictEqual(INITIAL_TODOS);
920
+ await pending;
921
+ expect(readCache(setup.client, scoped)).toStrictEqual(INITIAL_TODOS);
922
+ });
923
+
924
+ it("should never touch the entries of another client", async () => {
925
+ const first = createSetup();
926
+ const second = createSetup();
927
+ mockRequest(first.updateTodo, { data: createTodo(1) });
928
+
929
+ await first.updateTodo.send({
930
+ params: { todoId: 1 },
931
+ payload: {},
932
+ optimistic: [optimistic(first.getTodos).remove(1)],
933
+ });
934
+
935
+ expect(first.todos()).toHaveLength(2);
936
+ expect(second.todos()).toStrictEqual(INITIAL_TODOS);
937
+ expect(second.invalidate).not.toHaveBeenCalled();
938
+ });
939
+
940
+ it("should change nothing in server mode, where unscoped entries are not cached", async () => {
941
+ const client = new Client({ url: "shared-base-url", mode: "server" });
942
+ const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
943
+ const mutation = client
944
+ .createRequest<{ response: Todo }>()({ endpoint: "/todos/:todoId", method: "PATCH" })
945
+ .setMock(() => ({ error: new Error("Failed"), status: 500, success: false }), {
946
+ requestTime: 0,
947
+ responseTime: 0,
948
+ });
949
+ seedCache(client, getTodos, INITIAL_TODOS);
950
+
951
+ const response = await mutation.send({
952
+ params: { todoId: 1 },
953
+ optimistic: [
954
+ optimistic(getTodos)
955
+ .remove(1)
956
+ .rollback(({ previous }) => previous),
957
+ ],
958
+ });
959
+
960
+ expect(response.status).toBe(500);
961
+ expect(readCache(client, getTodos)).toBeUndefined();
962
+ });
963
+ });
964
+
965
+ describe("when counting cache events", () => {
966
+ it("should emit exactly one event per visible change", async () => {
967
+ const setup = createSetup();
968
+ const events = countDataEvents(setup, setup.getTodos);
969
+ const request = setup.updateTodo.setParams({ todoId: 1 }).setOptimistic(() => [
970
+ optimistic(setup.getTodos).patch(99, { done: true }),
971
+ optimistic(setup.getTodos)
972
+ .patch(1, { done: true })
973
+ .rollback(({ previous }) => previous),
974
+ ]);
975
+ mockRequest(request, { status: 500 });
976
+
977
+ await request.send({ payload: {} });
978
+
979
+ expect(events).toStrictEqual([
980
+ [{ ...INITIAL_TODOS[0], done: true }, INITIAL_TODOS[1], INITIAL_TODOS[2]],
981
+ INITIAL_TODOS,
982
+ ]);
983
+ });
984
+
985
+ it("should keep the staleness of the entry", async () => {
986
+ const setup = createSetup();
987
+ setup.client.cache.invalidate(setup.getTodos);
988
+ setup.invalidate.mockClear();
989
+ mockRequest(setup.updateTodo, { data: createTodo(1), delay: 20 });
990
+
991
+ const pending = setup.updateTodo.send({
992
+ params: { todoId: 1 },
993
+ payload: {},
994
+ optimistic: [optimistic(setup.getTodos).remove(1)],
995
+ });
996
+
997
+ expect(setup.client.cache.get(setup.getTodos.cacheKey)?.staleTime).toBe(0);
998
+ await pending;
999
+ });
1000
+ });
1001
+ });