@hyper-fetch/react 9.6.1 → 9.6.2
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.
- package/__tests__/features/helpers/use-tracked-state/use-tacked-state.actions.spec.ts +1 -1
- package/__tests__/features/helpers/use-tracked-state/use-tracked-state.keys.spec.ts +294 -0
- package/__tests__/features/helpers/utils.spec.ts +127 -0
- package/__tests__/features/provider/provider.config.spec.tsx +172 -0
- package/__tests__/features/use-app-manager/use-app-manager.events.spec.tsx +497 -0
- package/__tests__/features/use-cache/use-cache.state.spec.tsx +326 -0
- package/__tests__/features/use-emitter/use-emitter.lifecycle.spec.tsx +417 -0
- package/__tests__/features/use-fetch/use-fetch.bounce-timers.spec.ts +199 -0
- package/__tests__/features/use-fetch/use-fetch.cache-events.spec.ts +212 -0
- package/__tests__/features/use-fetch/use-fetch.callbacks.spec.tsx +359 -0
- package/__tests__/features/use-fetch/use-fetch.hydration.spec.tsx +126 -0
- package/__tests__/features/use-fetch/use-fetch.infinite.spec.ts +146 -0
- package/__tests__/features/use-fetch/use-fetch.initial-state.spec.ts +340 -0
- package/__tests__/features/use-fetch/use-fetch.keys.spec.tsx +559 -0
- package/__tests__/features/use-fetch/use-fetch.lifecycle.spec.ts +348 -0
- package/__tests__/features/use-fetch/use-fetch.mounting.spec.tsx +411 -0
- package/__tests__/features/use-fetch/use-fetch.pagination.spec.ts +177 -0
- package/__tests__/features/use-fetch/use-fetch.refresh-interval.spec.ts +355 -0
- package/__tests__/features/use-fetch/use-fetch.response-order.spec.ts +105 -0
- package/__tests__/features/use-fetch/use-fetch.retry.spec.ts +235 -0
- package/__tests__/features/use-fetch/use-fetch.return-types.spec.ts +186 -0
- package/__tests__/features/use-fetch/use-fetch.scope.spec.ts +333 -0
- package/__tests__/features/use-fetch/use-fetch.ssr.spec.tsx +195 -0
- package/__tests__/features/use-fetch/use-fetch.suspense-edge.spec.tsx +391 -0
- package/__tests__/features/use-fetch/use-fetch.throwing-callbacks.spec.tsx +112 -0
- package/__tests__/features/use-fetch/use-fetch.tracking.spec.tsx +364 -0
- package/__tests__/features/use-fetch/use-fetch.window-events.spec.ts +300 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.parity.spec.tsx +1027 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.resubscribe.spec.tsx +267 -0
- package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +64 -1
- package/__tests__/features/use-is-fetching/use-is-fetching.lifecycle.spec.tsx +301 -0
- package/__tests__/features/use-listener/use-listener.lifecycle.spec.tsx +507 -0
- package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +89 -0
- package/__tests__/features/use-queue/use-queue.controls.spec.tsx +593 -0
- package/__tests__/features/use-queue/use-queue.list.spec.tsx +560 -0
- package/__tests__/features/use-queue/use-queue.progress.spec.tsx +650 -0
- package/__tests__/features/use-submit/use-submit.abort.spec.tsx +270 -0
- package/__tests__/features/use-submit/use-submit.actions.spec.tsx +446 -0
- package/__tests__/features/use-submit/use-submit.arguments.spec.tsx +732 -0
- package/__tests__/features/use-submit/use-submit.bounce.spec.tsx +644 -0
- package/__tests__/features/use-submit/use-submit.callbacks.spec.tsx +860 -0
- package/__tests__/features/use-submit/use-submit.chaining.spec.tsx +167 -0
- package/__tests__/features/use-submit/use-submit.double-submit.spec.tsx +552 -0
- package/__tests__/features/use-submit/use-submit.offline.spec.tsx +285 -0
- package/__tests__/features/use-submit/use-submit.optimistic-cache.spec.tsx +619 -0
- package/__tests__/features/use-submit/use-submit.optimistic-settlement.spec.ts +6 -0
- package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +5 -1
- package/__tests__/features/use-submit/use-submit.state.spec.tsx +1025 -0
- package/__tests__/features/use-submit/use-submit.submit-types.spec.ts +194 -0
- package/__tests__/features/use-submit/use-submit.submitting.spec.tsx +180 -0
- package/__tests__/utils/gate.utils.ts +103 -0
- package/__tests__/utils/gated-client.utils.ts +158 -0
- package/__tests__/utils/helpers.utils.ts +19 -0
- package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
- package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
- package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
- package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
- package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +8 -0
- package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
- package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
- package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +3 -0
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +5 -3
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +11 -1
- package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -1
- package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
- package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -1
- package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
- package/dist/index.mjs +630 -346
- package/dist/index.mjs.map +1 -1
- package/dist/provider/provider.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/helpers/use-request-events/use-request-events.hooks.ts +141 -28
- package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
- package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +148 -101
- package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +26 -5
- package/src/hooks/use-cache/use-cache.hooks.ts +20 -5
- package/src/hooks/use-fetch/use-fetch.hooks.ts +194 -113
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +55 -26
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +35 -29
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +5 -3
- package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +25 -1
- package/src/hooks/use-listener/use-listener.hooks.ts +2 -1
- package/src/hooks/use-queue/use-queue.hooks.ts +85 -60
- package/src/hooks/use-submit/use-submit.hooks.ts +163 -53
- package/src/provider/provider.tsx +9 -1
- package/__tests__/features/use-fetch/use-fetch.pagination.ts +0 -36
- package/__tests__/features/use-fetch/use-fetch.retry.ts +0 -38
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
import { act, renderHook, waitFor } from "@testing-library/react";
|
|
2
|
+
import { useFetch } from "hooks/use-fetch";
|
|
3
|
+
import { useSubmit } from "hooks/use-submit";
|
|
4
|
+
|
|
5
|
+
import { createGatedClient } from "../../utils/gated-client.utils";
|
|
6
|
+
|
|
7
|
+
type User = { id: number; name: string };
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A list (`GET /users`) rendered with useFetch and a mutation (`POST /users`) rendered with useSubmit in one tree.
|
|
11
|
+
* The mutation adds the new user to the cached list optimistically and describes how to take it back.
|
|
12
|
+
*/
|
|
13
|
+
const setup = (options?: { retry?: number; retryTime?: number; cancelable?: boolean; invalidate?: boolean }) => {
|
|
14
|
+
const gated = createGatedClient();
|
|
15
|
+
const { client } = gated;
|
|
16
|
+
const getUsers = client.createRequest<{ response: User[] }>()({ endpoint: "/users" });
|
|
17
|
+
const rollbackSpy = vi.fn();
|
|
18
|
+
let temporaryId = 0;
|
|
19
|
+
|
|
20
|
+
const createUser = client
|
|
21
|
+
.createRequest<{ response: User; payload: { name: string } }>()({
|
|
22
|
+
endpoint: "/users",
|
|
23
|
+
method: "POST",
|
|
24
|
+
retry: options?.retry ?? 0,
|
|
25
|
+
retryTime: options?.retryTime ?? 0,
|
|
26
|
+
cancelable: options?.cancelable ?? false,
|
|
27
|
+
})
|
|
28
|
+
.setOptimistic(({ payload }) => {
|
|
29
|
+
temporaryId -= 1;
|
|
30
|
+
const optimisticUser = { id: temporaryId, name: payload.name };
|
|
31
|
+
client.cache.update(getUsers, (previous) => ({ data: [...(previous?.data ?? []), optimisticUser] }));
|
|
32
|
+
|
|
33
|
+
return {
|
|
34
|
+
context: { optimisticUser },
|
|
35
|
+
rollback: () => {
|
|
36
|
+
rollbackSpy(optimisticUser.name);
|
|
37
|
+
client.cache.update(getUsers, (previous) => ({
|
|
38
|
+
data: (previous?.data ?? []).filter((user) => user.id !== optimisticUser.id),
|
|
39
|
+
}));
|
|
40
|
+
},
|
|
41
|
+
invalidate: options?.invalidate === false ? [] : [getUsers],
|
|
42
|
+
};
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
const getCalls = (method: string) => gated.calls.filter((call) => call.request.method === method);
|
|
46
|
+
|
|
47
|
+
/** Renders the list with the mutation and answers the first list request */
|
|
48
|
+
const renderPage = async (users: User[] = [{ id: 1, name: "Maciej" }]) => {
|
|
49
|
+
const spies = { success: vi.fn(), error: vi.fn(), abort: vi.fn(), finished: vi.fn() };
|
|
50
|
+
const view = renderHook(() => {
|
|
51
|
+
const list = useFetch(getUsers, { dependencyTracking: false });
|
|
52
|
+
const create = useSubmit(createUser, { dependencyTracking: false });
|
|
53
|
+
create.onSubmitSuccess(spies.success);
|
|
54
|
+
create.onSubmitError(spies.error);
|
|
55
|
+
create.onSubmitAbort(spies.abort);
|
|
56
|
+
create.onSubmitFinished(spies.finished);
|
|
57
|
+
return { list, create };
|
|
58
|
+
});
|
|
59
|
+
await waitFor(() => {
|
|
60
|
+
expect(getCalls("GET")).toHaveLength(1);
|
|
61
|
+
});
|
|
62
|
+
act(() => {
|
|
63
|
+
getCalls("GET")[0].succeed(users);
|
|
64
|
+
});
|
|
65
|
+
await waitFor(() => {
|
|
66
|
+
expect(view.result.current.list.data).toStrictEqual(users);
|
|
67
|
+
});
|
|
68
|
+
const getNames = () => (view.result.current.list.data ?? []).map((user) => user.name);
|
|
69
|
+
return { ...view, spies, getNames };
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const waitForPost = async (index: number) => {
|
|
73
|
+
await waitFor(() => {
|
|
74
|
+
expect(getCalls("POST").length).toBeGreaterThan(index);
|
|
75
|
+
});
|
|
76
|
+
return getCalls("POST")[index];
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
return { ...gated, getUsers, createUser, rollbackSpy, getCalls, renderPage, waitForPost };
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** Run the pending timers and promise callbacks - for the tests using fake timers */
|
|
83
|
+
const advance = async (time = 0) => {
|
|
84
|
+
await act(async () => {
|
|
85
|
+
await vi.advanceTimersByTimeAsync(time);
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
describe("useSubmit [ Optimistic cache ]", () => {
|
|
90
|
+
afterEach(() => {
|
|
91
|
+
vi.useRealTimers();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe("when the submit starts", () => {
|
|
95
|
+
it("should show the optimistic change in the list before the response comes", async () => {
|
|
96
|
+
const { renderPage, waitForPost } = setup();
|
|
97
|
+
const { result, getNames } = await renderPage();
|
|
98
|
+
|
|
99
|
+
act(() => {
|
|
100
|
+
result.current.create.submit({ payload: { name: "Kacper" } });
|
|
101
|
+
});
|
|
102
|
+
const call = await waitForPost(0);
|
|
103
|
+
|
|
104
|
+
expect(call.settled).toBeFalse();
|
|
105
|
+
expect(getNames()).toStrictEqual(["Maciej", "Kacper"]);
|
|
106
|
+
expect(result.current.create.submitting).toBeTrue();
|
|
107
|
+
});
|
|
108
|
+
it("should not refetch the list when applying the optimistic change", async () => {
|
|
109
|
+
const { renderPage, waitForPost, getCalls } = setup();
|
|
110
|
+
const { result } = await renderPage();
|
|
111
|
+
|
|
112
|
+
act(() => {
|
|
113
|
+
result.current.create.submit({ payload: { name: "Kacper" } });
|
|
114
|
+
});
|
|
115
|
+
await waitForPost(0);
|
|
116
|
+
|
|
117
|
+
expect(getCalls("GET")).toHaveLength(1);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
describe("when the submit succeeds", () => {
|
|
122
|
+
it("should refetch the invalidated list once", async () => {
|
|
123
|
+
const { renderPage, waitForPost, getCalls } = setup();
|
|
124
|
+
const { result } = await renderPage();
|
|
125
|
+
let promise: Promise<unknown> = Promise.resolve();
|
|
126
|
+
act(() => {
|
|
127
|
+
promise = result.current.create.submit({ payload: { name: "Kacper" } });
|
|
128
|
+
});
|
|
129
|
+
const call = await waitForPost(0);
|
|
130
|
+
|
|
131
|
+
await act(async () => {
|
|
132
|
+
call.succeed({ id: 2, name: "Kacper" });
|
|
133
|
+
await promise;
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
await waitFor(() => {
|
|
137
|
+
expect(getCalls("GET")).toHaveLength(2);
|
|
138
|
+
});
|
|
139
|
+
expect(getCalls("GET")[1].settled).toBeFalse();
|
|
140
|
+
});
|
|
141
|
+
it("should replace the optimistic item with the data from the server", async () => {
|
|
142
|
+
const { renderPage, waitForPost, getCalls } = setup();
|
|
143
|
+
const { result, getNames } = await renderPage();
|
|
144
|
+
let promise: Promise<unknown> = Promise.resolve();
|
|
145
|
+
act(() => {
|
|
146
|
+
promise = result.current.create.submit({ payload: { name: "Kacper" } });
|
|
147
|
+
});
|
|
148
|
+
const call = await waitForPost(0);
|
|
149
|
+
await act(async () => {
|
|
150
|
+
call.succeed({ id: 2, name: "Kacper" });
|
|
151
|
+
await promise;
|
|
152
|
+
});
|
|
153
|
+
await waitFor(() => {
|
|
154
|
+
expect(getCalls("GET")).toHaveLength(2);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
act(() => {
|
|
158
|
+
getCalls("GET")[1].succeed([
|
|
159
|
+
{ id: 1, name: "Maciej" },
|
|
160
|
+
{ id: 2, name: "Kacper (saved)" },
|
|
161
|
+
]);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
await waitFor(() => {
|
|
165
|
+
expect(getNames()).toStrictEqual(["Maciej", "Kacper (saved)"]);
|
|
166
|
+
});
|
|
167
|
+
expect(result.current.list.data?.map((user) => user.id)).toStrictEqual([1, 2]);
|
|
168
|
+
});
|
|
169
|
+
it("should keep the optimistic item until the refetch is done", async () => {
|
|
170
|
+
const { renderPage, waitForPost, getCalls } = setup();
|
|
171
|
+
const { result, getNames } = await renderPage();
|
|
172
|
+
let promise: Promise<unknown> = Promise.resolve();
|
|
173
|
+
act(() => {
|
|
174
|
+
promise = result.current.create.submit({ payload: { name: "Kacper" } });
|
|
175
|
+
});
|
|
176
|
+
const call = await waitForPost(0);
|
|
177
|
+
|
|
178
|
+
await act(async () => {
|
|
179
|
+
call.succeed({ id: 2, name: "Kacper" });
|
|
180
|
+
await promise;
|
|
181
|
+
});
|
|
182
|
+
await waitFor(() => {
|
|
183
|
+
expect(getCalls("GET")).toHaveLength(2);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
expect(getNames()).toStrictEqual(["Maciej", "Kacper"]);
|
|
187
|
+
});
|
|
188
|
+
it("should not roll back", async () => {
|
|
189
|
+
const { renderPage, waitForPost, rollbackSpy } = setup();
|
|
190
|
+
const { result } = await renderPage();
|
|
191
|
+
let promise: Promise<unknown> = Promise.resolve();
|
|
192
|
+
act(() => {
|
|
193
|
+
promise = result.current.create.submit({ payload: { name: "Kacper" } });
|
|
194
|
+
});
|
|
195
|
+
const call = await waitForPost(0);
|
|
196
|
+
|
|
197
|
+
await act(async () => {
|
|
198
|
+
call.succeed({ id: 2, name: "Kacper" });
|
|
199
|
+
await promise;
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
expect(rollbackSpy).not.toHaveBeenCalled();
|
|
203
|
+
});
|
|
204
|
+
it("should pass the mutation context to the callbacks", async () => {
|
|
205
|
+
const { renderPage, waitForPost } = setup();
|
|
206
|
+
const { result, spies } = await renderPage();
|
|
207
|
+
let promise: Promise<unknown> = Promise.resolve();
|
|
208
|
+
act(() => {
|
|
209
|
+
promise = result.current.create.submit({ payload: { name: "Kacper" } });
|
|
210
|
+
});
|
|
211
|
+
const call = await waitForPost(0);
|
|
212
|
+
|
|
213
|
+
await act(async () => {
|
|
214
|
+
call.succeed({ id: 2, name: "Kacper" });
|
|
215
|
+
await promise;
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
const expectedContext = { optimisticUser: { id: -1, name: "Kacper" } };
|
|
219
|
+
expect(spies.success.mock.calls[0][0].mutationContext).toStrictEqual(expectedContext);
|
|
220
|
+
expect(spies.finished.mock.calls[0][0].mutationContext).toStrictEqual(expectedContext);
|
|
221
|
+
});
|
|
222
|
+
it("should not refetch anything when nothing is invalidated", async () => {
|
|
223
|
+
vi.useFakeTimers();
|
|
224
|
+
const { getCalls, getUsers, createUser } = setup({ invalidate: false });
|
|
225
|
+
const { result } = renderHook(() => ({
|
|
226
|
+
list: useFetch(getUsers, { dependencyTracking: false }),
|
|
227
|
+
create: useSubmit(createUser, { dependencyTracking: false }),
|
|
228
|
+
}));
|
|
229
|
+
await advance();
|
|
230
|
+
getCalls("GET")[0].succeed([{ id: 1, name: "Maciej" }]);
|
|
231
|
+
await advance();
|
|
232
|
+
|
|
233
|
+
act(() => {
|
|
234
|
+
result.current.create.submit({ payload: { name: "Kacper" } });
|
|
235
|
+
});
|
|
236
|
+
await advance();
|
|
237
|
+
getCalls("POST")[0].succeed({ id: 2, name: "Kacper" });
|
|
238
|
+
await advance(1000);
|
|
239
|
+
|
|
240
|
+
expect(getCalls("GET")).toHaveLength(1);
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
describe("when the submit fails", () => {
|
|
245
|
+
it("should roll the list back", async () => {
|
|
246
|
+
const { renderPage, waitForPost, rollbackSpy } = setup();
|
|
247
|
+
const { result, getNames } = await renderPage();
|
|
248
|
+
let promise: Promise<unknown> = Promise.resolve();
|
|
249
|
+
act(() => {
|
|
250
|
+
promise = result.current.create.submit({ payload: { name: "Kacper" } });
|
|
251
|
+
});
|
|
252
|
+
const call = await waitForPost(0);
|
|
253
|
+
expect(getNames()).toStrictEqual(["Maciej", "Kacper"]);
|
|
254
|
+
|
|
255
|
+
await act(async () => {
|
|
256
|
+
call.fail({ message: "Nope" }, 400);
|
|
257
|
+
await promise;
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
await waitFor(() => {
|
|
261
|
+
expect(getNames()).toStrictEqual(["Maciej"]);
|
|
262
|
+
});
|
|
263
|
+
expect(rollbackSpy).toHaveBeenCalledTimes(1);
|
|
264
|
+
});
|
|
265
|
+
it("should roll back before calling the error callback", async () => {
|
|
266
|
+
const { renderPage, waitForPost, rollbackSpy } = setup();
|
|
267
|
+
const { result, spies } = await renderPage();
|
|
268
|
+
let promise: Promise<unknown> = Promise.resolve();
|
|
269
|
+
act(() => {
|
|
270
|
+
promise = result.current.create.submit({ payload: { name: "Kacper" } });
|
|
271
|
+
});
|
|
272
|
+
const call = await waitForPost(0);
|
|
273
|
+
|
|
274
|
+
await act(async () => {
|
|
275
|
+
call.fail({ message: "Nope" }, 400);
|
|
276
|
+
await promise;
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
expect(spies.error).toHaveBeenCalledTimes(1);
|
|
280
|
+
expect(rollbackSpy.mock.invocationCallOrder[0]).toBeLessThan(spies.error.mock.invocationCallOrder[0]);
|
|
281
|
+
expect(spies.error.mock.calls[0][0].mutationContext).toStrictEqual({
|
|
282
|
+
optimisticUser: { id: -1, name: "Kacper" },
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
it("should not refetch the list", async () => {
|
|
286
|
+
vi.useFakeTimers();
|
|
287
|
+
const { getCalls, getUsers, createUser } = setup();
|
|
288
|
+
const { result } = renderHook(() => ({
|
|
289
|
+
list: useFetch(getUsers, { dependencyTracking: false }),
|
|
290
|
+
create: useSubmit(createUser, { dependencyTracking: false }),
|
|
291
|
+
}));
|
|
292
|
+
await advance();
|
|
293
|
+
getCalls("GET")[0].succeed([{ id: 1, name: "Maciej" }]);
|
|
294
|
+
await advance();
|
|
295
|
+
|
|
296
|
+
act(() => {
|
|
297
|
+
result.current.create.submit({ payload: { name: "Kacper" } });
|
|
298
|
+
});
|
|
299
|
+
await advance();
|
|
300
|
+
getCalls("POST")[0].fail({ message: "Nope" }, 400);
|
|
301
|
+
await advance(1000);
|
|
302
|
+
|
|
303
|
+
expect(getCalls("GET")).toHaveLength(1);
|
|
304
|
+
expect(result.current.list.data).toStrictEqual([{ id: 1, name: "Maciej" }]);
|
|
305
|
+
});
|
|
306
|
+
it("should keep the optimistic change while the request waits for a retry", async () => {
|
|
307
|
+
vi.useFakeTimers();
|
|
308
|
+
const { getCalls, getUsers, createUser, rollbackSpy } = setup({ retry: 1, retryTime: 5000 });
|
|
309
|
+
const { result } = renderHook(() => ({
|
|
310
|
+
list: useFetch(getUsers, { dependencyTracking: false }),
|
|
311
|
+
create: useSubmit(createUser, { dependencyTracking: false }),
|
|
312
|
+
}));
|
|
313
|
+
await advance();
|
|
314
|
+
getCalls("GET")[0].succeed([{ id: 1, name: "Maciej" }]);
|
|
315
|
+
await advance();
|
|
316
|
+
act(() => {
|
|
317
|
+
result.current.create.submit({ payload: { name: "Kacper" } });
|
|
318
|
+
});
|
|
319
|
+
await advance();
|
|
320
|
+
|
|
321
|
+
getCalls("POST")[0].fail({ message: "Temporary" }, 503);
|
|
322
|
+
await advance();
|
|
323
|
+
|
|
324
|
+
expect(rollbackSpy).not.toHaveBeenCalled();
|
|
325
|
+
expect(result.current.list.data?.map((user) => user.name)).toStrictEqual(["Maciej", "Kacper"]);
|
|
326
|
+
});
|
|
327
|
+
it("should roll back after the last retry fails", async () => {
|
|
328
|
+
vi.useFakeTimers();
|
|
329
|
+
const { getCalls, getUsers, createUser, rollbackSpy } = setup({ retry: 1, retryTime: 5000 });
|
|
330
|
+
const { result } = renderHook(() => ({
|
|
331
|
+
list: useFetch(getUsers, { dependencyTracking: false }),
|
|
332
|
+
create: useSubmit(createUser, { dependencyTracking: false }),
|
|
333
|
+
}));
|
|
334
|
+
await advance();
|
|
335
|
+
getCalls("GET")[0].succeed([{ id: 1, name: "Maciej" }]);
|
|
336
|
+
await advance();
|
|
337
|
+
act(() => {
|
|
338
|
+
result.current.create.submit({ payload: { name: "Kacper" } });
|
|
339
|
+
});
|
|
340
|
+
await advance();
|
|
341
|
+
getCalls("POST")[0].fail({ message: "Temporary" }, 503);
|
|
342
|
+
await advance(5000);
|
|
343
|
+
|
|
344
|
+
getCalls("POST")[1].fail({ message: "Still down" }, 503);
|
|
345
|
+
await advance();
|
|
346
|
+
|
|
347
|
+
expect(rollbackSpy).toHaveBeenCalledTimes(1);
|
|
348
|
+
expect(result.current.list.data?.map((user) => user.name)).toStrictEqual(["Maciej"]);
|
|
349
|
+
});
|
|
350
|
+
it("should run the optimistic callback once for a retried request", async () => {
|
|
351
|
+
vi.useFakeTimers();
|
|
352
|
+
const { getCalls, getUsers, createUser } = setup({ retry: 1, retryTime: 5000 });
|
|
353
|
+
const { result } = renderHook(() => ({
|
|
354
|
+
list: useFetch(getUsers, { dependencyTracking: false }),
|
|
355
|
+
create: useSubmit(createUser, { dependencyTracking: false }),
|
|
356
|
+
}));
|
|
357
|
+
await advance();
|
|
358
|
+
getCalls("GET")[0].succeed([{ id: 1, name: "Maciej" }]);
|
|
359
|
+
await advance();
|
|
360
|
+
act(() => {
|
|
361
|
+
result.current.create.submit({ payload: { name: "Kacper" } });
|
|
362
|
+
});
|
|
363
|
+
await advance();
|
|
364
|
+
getCalls("POST")[0].fail({ message: "Temporary" }, 503);
|
|
365
|
+
await advance(5000);
|
|
366
|
+
|
|
367
|
+
expect(getCalls("POST")).toHaveLength(2);
|
|
368
|
+
expect(result.current.list.data?.map((user) => user.name)).toStrictEqual(["Maciej", "Kacper"]);
|
|
369
|
+
});
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
describe("when the submit gets aborted", () => {
|
|
373
|
+
it("should roll the list back after abort()", async () => {
|
|
374
|
+
const { renderPage, waitForPost, rollbackSpy } = setup();
|
|
375
|
+
const { result, getNames } = await renderPage();
|
|
376
|
+
act(() => {
|
|
377
|
+
result.current.create.submit({ payload: { name: "Kacper" } });
|
|
378
|
+
});
|
|
379
|
+
await waitForPost(0);
|
|
380
|
+
expect(getNames()).toStrictEqual(["Maciej", "Kacper"]);
|
|
381
|
+
|
|
382
|
+
act(() => {
|
|
383
|
+
result.current.create.abort();
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
await waitFor(() => {
|
|
387
|
+
expect(getNames()).toStrictEqual(["Maciej"]);
|
|
388
|
+
});
|
|
389
|
+
expect(rollbackSpy).toHaveBeenCalledTimes(1);
|
|
390
|
+
});
|
|
391
|
+
it("should roll back the request replaced by a newer cancelable submit", async () => {
|
|
392
|
+
const { renderPage, waitForPost, rollbackSpy } = setup({ cancelable: true });
|
|
393
|
+
const { result, getNames, spies } = await renderPage();
|
|
394
|
+
act(() => {
|
|
395
|
+
result.current.create.submit({ payload: { name: "Kacper" } });
|
|
396
|
+
});
|
|
397
|
+
await waitForPost(0);
|
|
398
|
+
|
|
399
|
+
act(() => {
|
|
400
|
+
result.current.create.submit({ payload: { name: "Albert" } });
|
|
401
|
+
});
|
|
402
|
+
await waitForPost(1);
|
|
403
|
+
|
|
404
|
+
await waitFor(() => {
|
|
405
|
+
expect(spies.abort).toHaveBeenCalledTimes(1);
|
|
406
|
+
});
|
|
407
|
+
expect(rollbackSpy).toHaveBeenCalledTimes(1);
|
|
408
|
+
expect(rollbackSpy).toHaveBeenCalledWith("Kacper");
|
|
409
|
+
expect(getNames()).toStrictEqual(["Maciej", "Albert"]);
|
|
410
|
+
expect(spies.abort.mock.calls[0][0].mutationContext).toStrictEqual({
|
|
411
|
+
optimisticUser: { id: -1, name: "Kacper" },
|
|
412
|
+
});
|
|
413
|
+
});
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
describe("when two optimistic submits overlap", () => {
|
|
417
|
+
it("should show both optimistic changes", async () => {
|
|
418
|
+
const { renderPage, waitForPost } = setup();
|
|
419
|
+
const { result, getNames } = await renderPage();
|
|
420
|
+
|
|
421
|
+
act(() => {
|
|
422
|
+
result.current.create.submit({ payload: { name: "Kacper" } });
|
|
423
|
+
result.current.create.submit({ payload: { name: "Albert" } });
|
|
424
|
+
});
|
|
425
|
+
await waitForPost(1);
|
|
426
|
+
|
|
427
|
+
expect(getNames()).toStrictEqual(["Maciej", "Kacper", "Albert"]);
|
|
428
|
+
});
|
|
429
|
+
it("should roll back only the failed one", async () => {
|
|
430
|
+
const { renderPage, waitForPost, rollbackSpy } = setup({ invalidate: false });
|
|
431
|
+
const { result, getNames } = await renderPage();
|
|
432
|
+
let promises: Promise<unknown>[] = [];
|
|
433
|
+
act(() => {
|
|
434
|
+
promises = ["Kacper", "Albert"].map((name) => result.current.create.submit({ payload: { name } }));
|
|
435
|
+
});
|
|
436
|
+
await waitForPost(1);
|
|
437
|
+
const kacperCall = await waitForPost(0);
|
|
438
|
+
|
|
439
|
+
await act(async () => {
|
|
440
|
+
kacperCall.fail({ message: "Nope" }, 400);
|
|
441
|
+
await promises[0];
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
await waitFor(() => {
|
|
445
|
+
expect(getNames()).toStrictEqual(["Maciej", "Albert"]);
|
|
446
|
+
});
|
|
447
|
+
expect(rollbackSpy).toHaveBeenCalledTimes(1);
|
|
448
|
+
expect(rollbackSpy).toHaveBeenCalledWith("Kacper");
|
|
449
|
+
});
|
|
450
|
+
it("should restore the original list when both fail", async () => {
|
|
451
|
+
const { renderPage, waitForPost, rollbackSpy } = setup({ invalidate: false });
|
|
452
|
+
const { result, getNames } = await renderPage();
|
|
453
|
+
let promises: Promise<unknown>[] = [];
|
|
454
|
+
act(() => {
|
|
455
|
+
promises = ["Kacper", "Albert"].map((name) => result.current.create.submit({ payload: { name } }));
|
|
456
|
+
});
|
|
457
|
+
const albertCall = await waitForPost(1);
|
|
458
|
+
const kacperCall = await waitForPost(0);
|
|
459
|
+
|
|
460
|
+
await act(async () => {
|
|
461
|
+
albertCall.fail({ message: "Nope" }, 400);
|
|
462
|
+
kacperCall.fail({ message: "Nope" }, 400);
|
|
463
|
+
await Promise.all(promises);
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
await waitFor(() => {
|
|
467
|
+
expect(getNames()).toStrictEqual(["Maciej"]);
|
|
468
|
+
});
|
|
469
|
+
expect(rollbackSpy).toHaveBeenCalledTimes(2);
|
|
470
|
+
});
|
|
471
|
+
it("should give every submit its own mutation context", async () => {
|
|
472
|
+
const { renderPage, waitForPost } = setup({ invalidate: false });
|
|
473
|
+
const { result, spies } = await renderPage();
|
|
474
|
+
let promises: Promise<unknown>[] = [];
|
|
475
|
+
act(() => {
|
|
476
|
+
promises = ["Kacper", "Albert"].map((name) => result.current.create.submit({ payload: { name } }));
|
|
477
|
+
});
|
|
478
|
+
const albertCall = await waitForPost(1);
|
|
479
|
+
const kacperCall = await waitForPost(0);
|
|
480
|
+
|
|
481
|
+
await act(async () => {
|
|
482
|
+
kacperCall.succeed({ id: 2, name: "Kacper" });
|
|
483
|
+
albertCall.fail({ message: "Nope" }, 400);
|
|
484
|
+
await Promise.all(promises);
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
expect(spies.success.mock.calls[0][0].mutationContext.optimisticUser.name).toBe("Kacper");
|
|
488
|
+
expect(spies.error.mock.calls[0][0].mutationContext.optimisticUser.name).toBe("Albert");
|
|
489
|
+
});
|
|
490
|
+
});
|
|
491
|
+
|
|
492
|
+
describe("when the cache is updated by hand", () => {
|
|
493
|
+
it("should refetch the list once when the success callback invalidates it", async () => {
|
|
494
|
+
const { client, getUsers, getCalls } = setup();
|
|
495
|
+
const renameUser = client.createRequest<{ response: User; payload: { name: string } }>()({
|
|
496
|
+
endpoint: "/users/:userId",
|
|
497
|
+
method: "PATCH",
|
|
498
|
+
});
|
|
499
|
+
const { result } = renderHook(() => {
|
|
500
|
+
const list = useFetch(getUsers, { dependencyTracking: false });
|
|
501
|
+
const rename = useSubmit(renameUser, { dependencyTracking: false });
|
|
502
|
+
rename.onSubmitSuccess(() => {
|
|
503
|
+
client.cache.invalidate(getUsers);
|
|
504
|
+
});
|
|
505
|
+
return { list, rename };
|
|
506
|
+
});
|
|
507
|
+
await waitFor(() => {
|
|
508
|
+
expect(getCalls("GET")).toHaveLength(1);
|
|
509
|
+
});
|
|
510
|
+
act(() => {
|
|
511
|
+
getCalls("GET")[0].succeed([{ id: 1, name: "Maciej" }]);
|
|
512
|
+
});
|
|
513
|
+
await waitFor(() => {
|
|
514
|
+
expect(result.current.list.data).toStrictEqual([{ id: 1, name: "Maciej" }]);
|
|
515
|
+
});
|
|
516
|
+
|
|
517
|
+
let promise: Promise<unknown> = Promise.resolve();
|
|
518
|
+
act(() => {
|
|
519
|
+
promise = result.current.rename.submit({ payload: { name: "Maciek" }, params: { userId: 1 } });
|
|
520
|
+
});
|
|
521
|
+
await waitFor(() => {
|
|
522
|
+
expect(getCalls("PATCH")).toHaveLength(1);
|
|
523
|
+
});
|
|
524
|
+
await act(async () => {
|
|
525
|
+
getCalls("PATCH")[0].succeed({ id: 1, name: "Maciek" });
|
|
526
|
+
await promise;
|
|
527
|
+
});
|
|
528
|
+
await waitFor(() => {
|
|
529
|
+
expect(getCalls("GET")).toHaveLength(2);
|
|
530
|
+
});
|
|
531
|
+
act(() => {
|
|
532
|
+
getCalls("GET")[1].succeed([{ id: 1, name: "Maciek" }]);
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
await waitFor(() => {
|
|
536
|
+
expect(result.current.list.data).toStrictEqual([{ id: 1, name: "Maciek" }]);
|
|
537
|
+
});
|
|
538
|
+
expect(getCalls("GET")).toHaveLength(2);
|
|
539
|
+
});
|
|
540
|
+
it("should show the response written to the list cache without a refetch", async () => {
|
|
541
|
+
const { client, getUsers, getCalls } = setup();
|
|
542
|
+
const renameUser = client.createRequest<{ response: User; payload: { name: string } }>()({
|
|
543
|
+
endpoint: "/users/:userId",
|
|
544
|
+
method: "PATCH",
|
|
545
|
+
});
|
|
546
|
+
const { result } = renderHook(() => {
|
|
547
|
+
const list = useFetch(getUsers, { dependencyTracking: false });
|
|
548
|
+
const rename = useSubmit(renameUser, { dependencyTracking: false });
|
|
549
|
+
rename.onSubmitSuccess(({ response }) => {
|
|
550
|
+
client.cache.update(getUsers, (previous) => ({
|
|
551
|
+
data: (previous?.data ?? []).map((user) => (user.id === response.data.id ? response.data : user)),
|
|
552
|
+
}));
|
|
553
|
+
});
|
|
554
|
+
return { list, rename };
|
|
555
|
+
});
|
|
556
|
+
await waitFor(() => {
|
|
557
|
+
expect(getCalls("GET")).toHaveLength(1);
|
|
558
|
+
});
|
|
559
|
+
act(() => {
|
|
560
|
+
getCalls("GET")[0].succeed([
|
|
561
|
+
{ id: 1, name: "Maciej" },
|
|
562
|
+
{ id: 2, name: "Kacper" },
|
|
563
|
+
]);
|
|
564
|
+
});
|
|
565
|
+
await waitFor(() => {
|
|
566
|
+
expect(result.current.list.data).toHaveLength(2);
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
let promise: Promise<unknown> = Promise.resolve();
|
|
570
|
+
act(() => {
|
|
571
|
+
promise = result.current.rename.submit({ payload: { name: "Maciek" }, params: { userId: 1 } });
|
|
572
|
+
});
|
|
573
|
+
await waitFor(() => {
|
|
574
|
+
expect(getCalls("PATCH")).toHaveLength(1);
|
|
575
|
+
});
|
|
576
|
+
await act(async () => {
|
|
577
|
+
getCalls("PATCH")[0].succeed({ id: 1, name: "Maciek" });
|
|
578
|
+
await promise;
|
|
579
|
+
});
|
|
580
|
+
|
|
581
|
+
await waitFor(() => {
|
|
582
|
+
expect(result.current.list.data).toStrictEqual([
|
|
583
|
+
{ id: 1, name: "Maciek" },
|
|
584
|
+
{ id: 2, name: "Kacper" },
|
|
585
|
+
]);
|
|
586
|
+
});
|
|
587
|
+
expect(getCalls("GET")).toHaveLength(1);
|
|
588
|
+
});
|
|
589
|
+
it("should invalidate the cache of its own request with refetch()", async () => {
|
|
590
|
+
const { client, createUser } = setup();
|
|
591
|
+
const invalidateSpy = vi.spyOn(client.cache, "invalidate");
|
|
592
|
+
const { result } = renderHook(() => useSubmit(createUser, { dependencyTracking: false }));
|
|
593
|
+
|
|
594
|
+
act(() => {
|
|
595
|
+
result.current.refetch();
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
expect(invalidateSpy).toHaveBeenCalledTimes(1);
|
|
599
|
+
expect(invalidateSpy).toHaveBeenCalledWith(createUser);
|
|
600
|
+
});
|
|
601
|
+
it("should invalidate the request from the latest render with refetch()", async () => {
|
|
602
|
+
const { client } = setup();
|
|
603
|
+
const renameUser = client.createRequest<{ response: User }>()({ endpoint: "/users/:userId", method: "PATCH" });
|
|
604
|
+
const invalidateSpy = vi.spyOn(client.cache, "invalidate");
|
|
605
|
+
const { result, rerender } = renderHook(
|
|
606
|
+
({ userId }: { userId: number }) => useSubmit(renameUser.setParams({ userId }), { dependencyTracking: false }),
|
|
607
|
+
{ initialProps: { userId: 1 } },
|
|
608
|
+
);
|
|
609
|
+
const initialRefetch = result.current.refetch;
|
|
610
|
+
|
|
611
|
+
rerender({ userId: 2 });
|
|
612
|
+
act(() => {
|
|
613
|
+
initialRefetch();
|
|
614
|
+
});
|
|
615
|
+
|
|
616
|
+
expect((invalidateSpy.mock.calls[0][0] as typeof renameUser).endpoint).toBe("/users/2");
|
|
617
|
+
});
|
|
618
|
+
});
|
|
619
|
+
});
|
|
@@ -5,6 +5,8 @@ import { act, renderHook, waitFor } from "@testing-library/react";
|
|
|
5
5
|
import { useSubmit } from "hooks/use-submit";
|
|
6
6
|
import { StrictMode } from "react";
|
|
7
7
|
|
|
8
|
+
import { collectThrownErrors } from "../../utils/helpers.utils";
|
|
9
|
+
|
|
8
10
|
const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
|
|
9
11
|
|
|
10
12
|
const SERVER_ITEM = "server";
|
|
@@ -371,6 +373,7 @@ describe("useSubmit [ Optimistic settlement ]", () => {
|
|
|
371
373
|
});
|
|
372
374
|
|
|
373
375
|
it("should fire callbacks when rollback throws", async () => {
|
|
376
|
+
const thrown = collectThrownErrors();
|
|
374
377
|
const setup = createSetup();
|
|
375
378
|
setup.rollback.mockImplementation(() => {
|
|
376
379
|
throw new Error("Rollback failed");
|
|
@@ -392,6 +395,9 @@ describe("useSubmit [ Optimistic settlement ]", () => {
|
|
|
392
395
|
expect(onError).toHaveBeenCalledTimes(1);
|
|
393
396
|
expect(onFinished).toHaveBeenCalledTimes(1);
|
|
394
397
|
});
|
|
398
|
+
await waitFor(() => {
|
|
399
|
+
expect(thrown).toStrictEqual([new Error("Rollback failed")]);
|
|
400
|
+
});
|
|
395
401
|
});
|
|
396
402
|
});
|
|
397
403
|
|
|
@@ -2,7 +2,7 @@ import { createHttpMockingServer } from "@hyper-fetch/testing";
|
|
|
2
2
|
import { act, waitFor } from "@testing-library/react";
|
|
3
3
|
|
|
4
4
|
import { testSuccessState, testErrorState } from "../../shared";
|
|
5
|
-
import { client, createRequest, renderUseSubmit } from "../../utils";
|
|
5
|
+
import { client, collectThrownErrors, createRequest, renderUseSubmit } from "../../utils";
|
|
6
6
|
|
|
7
7
|
const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
|
|
8
8
|
|
|
@@ -122,6 +122,7 @@ describe("useSubmit [ Optimistic ]", () => {
|
|
|
122
122
|
});
|
|
123
123
|
|
|
124
124
|
it("should still fire onSubmitError when rollback throws", async () => {
|
|
125
|
+
const thrown = collectThrownErrors();
|
|
125
126
|
const errorSpy = vi.fn();
|
|
126
127
|
const optimisticRequest = request.setOptimistic(() => ({
|
|
127
128
|
context: { val: true },
|
|
@@ -141,6 +142,9 @@ describe("useSubmit [ Optimistic ]", () => {
|
|
|
141
142
|
await testErrorState(mock, response);
|
|
142
143
|
expect(errorSpy).toHaveBeenCalledTimes(1);
|
|
143
144
|
expect(errorSpy.mock.calls[0][0].mutationContext).toStrictEqual({ val: true });
|
|
145
|
+
await waitFor(() => {
|
|
146
|
+
expect(thrown).toStrictEqual([new Error("Rollback failed")]);
|
|
147
|
+
});
|
|
144
148
|
});
|
|
145
149
|
});
|
|
146
150
|
|