@hyper-fetch/react 9.6.1 → 9.7.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.
- 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-helpers.spec.tsx +455 -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.constants.d.ts +1 -1
- package/dist/hooks/use-submit/use-submit.constants.d.ts.map +1 -1
- package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
- package/dist/hooks/use-submit/use-submit.types.d.ts +6 -1
- package/dist/hooks/use-submit/use-submit.types.d.ts.map +1 -1
- package/dist/index.mjs +633 -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.constants.ts +3 -1
- package/src/hooks/use-submit/use-submit.hooks.ts +167 -53
- package/src/hooks/use-submit/use-submit.types.ts +6 -0
- 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,455 @@
|
|
|
1
|
+
import type { RequestInstance } from "@hyper-fetch/core";
|
|
2
|
+
import { Client, optimistic } from "@hyper-fetch/core";
|
|
3
|
+
import { act, renderHook, waitFor } from "@testing-library/react";
|
|
4
|
+
import { useFetch } from "hooks/use-fetch";
|
|
5
|
+
import { useInfiniteFetch } from "hooks/use-infinite-fetch";
|
|
6
|
+
import { useSubmit } from "hooks/use-submit";
|
|
7
|
+
import type { ReactNode } from "react";
|
|
8
|
+
import React, { StrictMode } from "react";
|
|
9
|
+
|
|
10
|
+
type Todo = { id: number; done: boolean; likes: number };
|
|
11
|
+
|
|
12
|
+
type Call = {
|
|
13
|
+
request: RequestInstance;
|
|
14
|
+
requestId: string;
|
|
15
|
+
respond: (response: { data?: unknown; error?: unknown }) => void;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const todo = (id: number, extra: Partial<Todo> = {}): Todo => ({ id, done: false, likes: 0, ...extra });
|
|
19
|
+
const SERVER = [todo(1), todo(2)];
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Requests wait until the test answers them, only the network part of the adapter is replaced
|
|
23
|
+
*/
|
|
24
|
+
const createSetup = () => {
|
|
25
|
+
const client = new Client({ url: "http://localhost:3000" });
|
|
26
|
+
const calls: Call[] = [];
|
|
27
|
+
|
|
28
|
+
client.adapter.setFetcher(({ request, requestId, onSuccess, onError, createAbortListener }) => {
|
|
29
|
+
let isFinished = false;
|
|
30
|
+
const extra = client.adapter.defaultExtra;
|
|
31
|
+
createAbortListener({ status: 0, extra, onAbort: () => (isFinished = true) });
|
|
32
|
+
calls.push({
|
|
33
|
+
request,
|
|
34
|
+
requestId,
|
|
35
|
+
respond: ({ data = null, error }) => {
|
|
36
|
+
if (isFinished) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
isFinished = true;
|
|
40
|
+
if (error) {
|
|
41
|
+
onError({ error, status: 500, extra });
|
|
42
|
+
} else {
|
|
43
|
+
onSuccess({ data, status: 200, extra });
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
const getTodos = client.createRequest<{ response: Todo[] }>()({ endpoint: "/todos" });
|
|
50
|
+
const toggle = client
|
|
51
|
+
.createRequest<{ response: Todo; payload: { done: boolean } }>()({ endpoint: "/todos/:todoId", method: "PATCH" })
|
|
52
|
+
.setOptimistic(({ params, payload }) => [
|
|
53
|
+
optimistic(getTodos)
|
|
54
|
+
.patch(params.todoId, payload)
|
|
55
|
+
.rollback(({ data, previous }) => {
|
|
56
|
+
const before = previous.find((item) => item.id === Number(params.todoId));
|
|
57
|
+
return data.map((item) => (item.id === Number(params.todoId) && before ? before : item));
|
|
58
|
+
}),
|
|
59
|
+
]);
|
|
60
|
+
|
|
61
|
+
const callsTo = (endpoint: string) => calls.filter((call) => call.request.endpoint === endpoint);
|
|
62
|
+
const lastCallTo = async (endpoint: string, count: number) => {
|
|
63
|
+
await waitFor(() => expect(callsTo(endpoint)).toHaveLength(count), { interval: 1 });
|
|
64
|
+
return callsTo(endpoint)[count - 1];
|
|
65
|
+
};
|
|
66
|
+
const answered = new Set<Call>();
|
|
67
|
+
const answer = async (call: Call, response: { data?: unknown; error?: unknown }) => {
|
|
68
|
+
answered.add(call);
|
|
69
|
+
await act(async () => {
|
|
70
|
+
call.respond(response);
|
|
71
|
+
});
|
|
72
|
+
};
|
|
73
|
+
/** Waits for the oldest call to the endpoint which is not answered yet */
|
|
74
|
+
const nextCallTo = async (endpoint: string) => {
|
|
75
|
+
await waitFor(() => expect(callsTo(endpoint).some((call) => !answered.has(call))).toBeTrue(), { interval: 1 });
|
|
76
|
+
return callsTo(endpoint).find((call) => !answered.has(call)) as Call;
|
|
77
|
+
};
|
|
78
|
+
const read = () => client.cache.get<Todo[], unknown>(getTodos.cacheKey)?.data;
|
|
79
|
+
|
|
80
|
+
return { client, calls, getTodos, toggle, callsTo, lastCallTo, nextCallTo, answer, read };
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
type Setup = ReturnType<typeof createSetup>;
|
|
84
|
+
|
|
85
|
+
/** A list and a toggle button in one component, with a log of the rendered list */
|
|
86
|
+
const renderTodos = (setup: Setup, options: { wrapper?: (props: { children: ReactNode }) => ReactNode } = {}) => {
|
|
87
|
+
const renders: (Todo[] | null)[] = [];
|
|
88
|
+
const rendered = renderHook(
|
|
89
|
+
() => {
|
|
90
|
+
const list = useFetch(setup.getTodos, { dependencyTracking: false });
|
|
91
|
+
const button = useSubmit(setup.toggle, { dependencyTracking: false });
|
|
92
|
+
renders.push(list.data);
|
|
93
|
+
return { list, button };
|
|
94
|
+
},
|
|
95
|
+
{ wrapper: options.wrapper },
|
|
96
|
+
);
|
|
97
|
+
return { ...rendered, renders };
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const loadList = async (setup: Setup, data: Todo[] = SERVER) => {
|
|
101
|
+
await setup.answer(await setup.nextCallTo("/todos"), { data });
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const doneOf = (list: Todo[] | null | undefined, id: number) => list?.find((item) => item.id === id)?.done;
|
|
105
|
+
|
|
106
|
+
describe("useSubmit [ Optimistic helpers ]", () => {
|
|
107
|
+
describe("when submitting", () => {
|
|
108
|
+
it("should show the change before the response and keep it without flicker on success", async () => {
|
|
109
|
+
const setup = createSetup();
|
|
110
|
+
const { result, renders } = renderTodos(setup);
|
|
111
|
+
await loadList(setup);
|
|
112
|
+
|
|
113
|
+
act(() => {
|
|
114
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
|
|
115
|
+
});
|
|
116
|
+
expect(doneOf(result.current.list.data, 1)).toBeTrue();
|
|
117
|
+
|
|
118
|
+
const mutation = await setup.lastCallTo("/todos/1", 1);
|
|
119
|
+
await setup.answer(mutation, { data: todo(1, { done: true }) });
|
|
120
|
+
|
|
121
|
+
// The refresh after the mutation reads the confirmed data
|
|
122
|
+
await loadList(setup, [todo(1, { done: true }), todo(2)]);
|
|
123
|
+
expect(doneOf(result.current.list.data, 1)).toBeTrue();
|
|
124
|
+
|
|
125
|
+
const firstOptimistic = renders.findIndex((list) => doneOf(list, 1) === true);
|
|
126
|
+
expect(renders.slice(firstOptimistic).every((list) => doneOf(list, 1) === true)).toBeTrue();
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("should revert on error and show the server data after the refresh", async () => {
|
|
130
|
+
const setup = createSetup();
|
|
131
|
+
const { result } = renderTodos(setup);
|
|
132
|
+
await loadList(setup);
|
|
133
|
+
|
|
134
|
+
act(() => {
|
|
135
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
|
|
136
|
+
});
|
|
137
|
+
const mutation = await setup.lastCallTo("/todos/1", 1);
|
|
138
|
+
await setup.answer(mutation, { error: new Error("Failed") });
|
|
139
|
+
|
|
140
|
+
expect(doneOf(result.current.list.data, 1)).toBeFalse();
|
|
141
|
+
await loadList(setup, [todo(1, { likes: 3 }), todo(2)]);
|
|
142
|
+
expect(result.current.list.data).toStrictEqual([todo(1, { likes: 3 }), todo(2)]);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("should settle a mutation of an unmounted component", async () => {
|
|
146
|
+
const setup = createSetup();
|
|
147
|
+
const { result, unmount } = renderTodos(setup);
|
|
148
|
+
await loadList(setup);
|
|
149
|
+
|
|
150
|
+
act(() => {
|
|
151
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
|
|
152
|
+
});
|
|
153
|
+
const mutation = await setup.lastCallTo("/todos/1", 1);
|
|
154
|
+
unmount();
|
|
155
|
+
await setup.answer(mutation, { error: new Error("Failed") });
|
|
156
|
+
|
|
157
|
+
expect(doneOf(setup.read(), 1)).toBeFalse();
|
|
158
|
+
|
|
159
|
+
// A remount shows the reverted value
|
|
160
|
+
const remounted = renderTodos(setup);
|
|
161
|
+
expect(doneOf(remounted.result.current.list.data, 1)).toBeFalse();
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it("should update every component reading the key", async () => {
|
|
165
|
+
const setup = createSetup();
|
|
166
|
+
const first = renderTodos(setup);
|
|
167
|
+
await loadList(setup);
|
|
168
|
+
const second = renderHook(() => useFetch(setup.getTodos, { dependencyTracking: false }));
|
|
169
|
+
|
|
170
|
+
act(() => {
|
|
171
|
+
first.result.current.button.submit({ params: { todoId: 2 }, payload: { done: true } });
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
expect(doneOf(first.result.current.list.data, 2)).toBeTrue();
|
|
175
|
+
expect(doneOf(second.result.current.data, 2)).toBeTrue();
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it("should apply the change once in StrictMode", async () => {
|
|
179
|
+
const setup = createSetup();
|
|
180
|
+
const like = setup.client
|
|
181
|
+
.createRequest<{ response: null }>()({ endpoint: "/like", method: "POST" })
|
|
182
|
+
.setOptimistic(() => [optimistic(setup.getTodos).increment(1, "likes", 1)]);
|
|
183
|
+
const wrapper = ({ children }: { children: ReactNode }) => <StrictMode>{children}</StrictMode>;
|
|
184
|
+
const { result } = renderHook(
|
|
185
|
+
() => ({
|
|
186
|
+
list: useFetch(setup.getTodos, { dependencyTracking: false }),
|
|
187
|
+
button: useSubmit(like, { dependencyTracking: false }),
|
|
188
|
+
}),
|
|
189
|
+
{ wrapper },
|
|
190
|
+
);
|
|
191
|
+
await waitFor(() => expect(setup.callsTo("/todos").length).toBeGreaterThan(0), { interval: 1 });
|
|
192
|
+
await Promise.all(setup.callsTo("/todos").map((call) => setup.answer(call, { data: SERVER })));
|
|
193
|
+
|
|
194
|
+
act(() => {
|
|
195
|
+
result.current.button.submit();
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
expect(result.current.list.data?.[0].likes).toBe(1);
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
describe("when toggling rapidly", () => {
|
|
203
|
+
it("should end on the server value after ten clicks with mixed outcomes", async () => {
|
|
204
|
+
const setup = createSetup();
|
|
205
|
+
const { result } = renderTodos(setup);
|
|
206
|
+
await loadList(setup);
|
|
207
|
+
let server = [...SERVER];
|
|
208
|
+
const outcomes = [true, false, true, true, false, false, true, false, true, false];
|
|
209
|
+
|
|
210
|
+
for (const [index] of outcomes.entries()) {
|
|
211
|
+
act(() => {
|
|
212
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: index % 2 === 0 } });
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
expect(doneOf(result.current.list.data, 1)).toBeFalse();
|
|
216
|
+
|
|
217
|
+
const mutations = await setup.lastCallTo("/todos/1", outcomes.length).then(() => setup.callsTo("/todos/1"));
|
|
218
|
+
// The server answers in reverse order
|
|
219
|
+
for (const index of [...outcomes.keys()].toReversed()) {
|
|
220
|
+
if (outcomes[index]) {
|
|
221
|
+
server = server.map((item) => (item.id === 1 ? { ...item, done: index % 2 === 0 } : item));
|
|
222
|
+
// eslint-disable-next-line no-await-in-loop
|
|
223
|
+
await setup.answer(mutations[index], { data: server[0] });
|
|
224
|
+
} else {
|
|
225
|
+
// eslint-disable-next-line no-await-in-loop
|
|
226
|
+
await setup.answer(mutations[index], { error: new Error("Failed") });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// One refresh after the last mutation
|
|
231
|
+
await loadList(setup, server);
|
|
232
|
+
expect(result.current.list.data).toStrictEqual(server);
|
|
233
|
+
expect(setup.callsTo("/todos")).toHaveLength(2);
|
|
234
|
+
});
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
describe("when the list is fetched during a pending change", () => {
|
|
238
|
+
it("should discard a manual refetch that started before the change settled", async () => {
|
|
239
|
+
const setup = createSetup();
|
|
240
|
+
const { result } = renderTodos(setup);
|
|
241
|
+
await loadList(setup);
|
|
242
|
+
|
|
243
|
+
act(() => {
|
|
244
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
|
|
245
|
+
});
|
|
246
|
+
act(() => {
|
|
247
|
+
result.current.list.refetch();
|
|
248
|
+
});
|
|
249
|
+
const refetch = await setup.lastCallTo("/todos", 2);
|
|
250
|
+
await setup.answer(refetch, { data: SERVER });
|
|
251
|
+
|
|
252
|
+
expect(doneOf(result.current.list.data, 1)).toBeTrue();
|
|
253
|
+
|
|
254
|
+
const mutation = await setup.lastCallTo("/todos/1", 1);
|
|
255
|
+
await setup.answer(mutation, { data: todo(1, { done: true }) });
|
|
256
|
+
await loadList(setup, [todo(1, { done: true }), todo(2)]);
|
|
257
|
+
expect(doneOf(result.current.list.data, 1)).toBeTrue();
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it("should discard a refetch on focus that started before the change settled", async () => {
|
|
261
|
+
const setup = createSetup();
|
|
262
|
+
const renders: (Todo[] | null)[] = [];
|
|
263
|
+
const { result } = renderHook(() => {
|
|
264
|
+
const list = useFetch(setup.getTodos, { dependencyTracking: false, refetchOnFocus: true });
|
|
265
|
+
const button = useSubmit(setup.toggle, { dependencyTracking: false });
|
|
266
|
+
renders.push(list.data);
|
|
267
|
+
return { list, button };
|
|
268
|
+
});
|
|
269
|
+
await loadList(setup);
|
|
270
|
+
|
|
271
|
+
act(() => {
|
|
272
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
|
|
273
|
+
});
|
|
274
|
+
act(() => {
|
|
275
|
+
setup.client.appManager.setFocused(false);
|
|
276
|
+
setup.client.appManager.setFocused(true);
|
|
277
|
+
});
|
|
278
|
+
const focusFetch = await setup.lastCallTo("/todos", 2);
|
|
279
|
+
const mutation = await setup.lastCallTo("/todos/1", 1);
|
|
280
|
+
await setup.answer(mutation, { data: todo(1, { done: true }) });
|
|
281
|
+
await setup.answer(focusFetch, { data: SERVER });
|
|
282
|
+
|
|
283
|
+
expect(doneOf(result.current.list.data, 1)).toBeTrue();
|
|
284
|
+
await loadList(setup, [todo(1, { done: true }), todo(2)]);
|
|
285
|
+
expect(doneOf(result.current.list.data, 1)).toBeTrue();
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it("should discard a polling refresh while the change is pending", async () => {
|
|
289
|
+
const setup = createSetup();
|
|
290
|
+
const { result } = renderHook(() => ({
|
|
291
|
+
list: useFetch(setup.getTodos, { dependencyTracking: false, refresh: true, refreshTime: 20 }),
|
|
292
|
+
button: useSubmit(setup.toggle, { dependencyTracking: false }),
|
|
293
|
+
}));
|
|
294
|
+
await loadList(setup);
|
|
295
|
+
|
|
296
|
+
act(() => {
|
|
297
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
|
|
298
|
+
});
|
|
299
|
+
const poll = await setup.lastCallTo("/todos", 2);
|
|
300
|
+
await setup.answer(poll, { data: SERVER });
|
|
301
|
+
|
|
302
|
+
expect(doneOf(result.current.list.data, 1)).toBeTrue();
|
|
303
|
+
const mutation = await setup.lastCallTo("/todos/1", 1);
|
|
304
|
+
await setup.answer(mutation, { error: new Error("Failed") });
|
|
305
|
+
expect(doneOf(result.current.list.data, 1)).toBeFalse();
|
|
306
|
+
});
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
describe("when passing optimistic to the hook", () => {
|
|
310
|
+
it("should use the hook option and let submit() override it", async () => {
|
|
311
|
+
const setup = createSetup();
|
|
312
|
+
const plain = setup.client.createRequest<{ response: null }>()({ endpoint: "/plain", method: "POST" });
|
|
313
|
+
const { result } = renderHook(() => ({
|
|
314
|
+
list: useFetch(setup.getTodos, { dependencyTracking: false }),
|
|
315
|
+
button: useSubmit(plain, {
|
|
316
|
+
dependencyTracking: false,
|
|
317
|
+
optimistic: [optimistic(setup.getTodos).patch(1, { likes: 1 })],
|
|
318
|
+
}),
|
|
319
|
+
}));
|
|
320
|
+
await loadList(setup);
|
|
321
|
+
|
|
322
|
+
act(() => {
|
|
323
|
+
result.current.button.submit();
|
|
324
|
+
});
|
|
325
|
+
expect(result.current.list.data?.[0].likes).toBe(1);
|
|
326
|
+
|
|
327
|
+
act(() => {
|
|
328
|
+
result.current.button.submit({ optimistic: [optimistic(setup.getTodos).patch(2, { likes: 5 })] });
|
|
329
|
+
});
|
|
330
|
+
expect(result.current.list.data?.map((item) => item.likes)).toStrictEqual([1, 5]);
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
it("should replace the request's callback with the hook option", async () => {
|
|
334
|
+
const setup = createSetup();
|
|
335
|
+
const { result } = renderHook(() => ({
|
|
336
|
+
list: useFetch(setup.getTodos, { dependencyTracking: false }),
|
|
337
|
+
button: useSubmit(setup.toggle, {
|
|
338
|
+
dependencyTracking: false,
|
|
339
|
+
optimistic: ({ params }) => [optimistic(setup.getTodos).remove(params.todoId)],
|
|
340
|
+
}),
|
|
341
|
+
}));
|
|
342
|
+
await loadList(setup);
|
|
343
|
+
|
|
344
|
+
act(() => {
|
|
345
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
expect(result.current.list.data).toStrictEqual([todo(2)]);
|
|
349
|
+
});
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
describe("when settling through useSubmit", () => {
|
|
353
|
+
it.each([
|
|
354
|
+
{ name: "success", response: { data: todo(1, { done: true }) }, done: true, reverted: false },
|
|
355
|
+
{ name: "final error", response: { error: new Error("Failed") }, done: false, reverted: true },
|
|
356
|
+
])("should settle $name", async ({ response, done }) => {
|
|
357
|
+
const setup = createSetup();
|
|
358
|
+
const { result } = renderTodos(setup);
|
|
359
|
+
await loadList(setup);
|
|
360
|
+
const onSettled = vi.fn();
|
|
361
|
+
|
|
362
|
+
act(() => {
|
|
363
|
+
result.current.button.onSubmitFinished(onSettled);
|
|
364
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
|
|
365
|
+
});
|
|
366
|
+
const mutation = await setup.lastCallTo("/todos/1", 1);
|
|
367
|
+
await setup.answer(mutation, response);
|
|
368
|
+
|
|
369
|
+
expect(doneOf(result.current.list.data, 1)).toBe(done);
|
|
370
|
+
expect(onSettled).toHaveBeenCalledTimes(1);
|
|
371
|
+
// The list is refetched once
|
|
372
|
+
await setup.lastCallTo("/todos", 2);
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
it("should settle abort", async () => {
|
|
376
|
+
const setup = createSetup();
|
|
377
|
+
const { result } = renderTodos(setup);
|
|
378
|
+
await loadList(setup);
|
|
379
|
+
|
|
380
|
+
act(() => {
|
|
381
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
|
|
382
|
+
});
|
|
383
|
+
await setup.lastCallTo("/todos/1", 1);
|
|
384
|
+
await act(async () => {
|
|
385
|
+
result.current.button.abort();
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
expect(doneOf(result.current.list.data, 1)).toBeFalse();
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
it("should keep the change while retrying", async () => {
|
|
392
|
+
const setup = createSetup();
|
|
393
|
+
const retried = setup.toggle.setRetry(1).setRetryTime(0);
|
|
394
|
+
const { result } = renderHook(() => ({
|
|
395
|
+
list: useFetch(setup.getTodos, { dependencyTracking: false }),
|
|
396
|
+
button: useSubmit(retried, { dependencyTracking: false }),
|
|
397
|
+
}));
|
|
398
|
+
await loadList(setup);
|
|
399
|
+
|
|
400
|
+
act(() => {
|
|
401
|
+
result.current.button.submit({ params: { todoId: 1 }, payload: { done: true } });
|
|
402
|
+
});
|
|
403
|
+
await setup.answer(await setup.lastCallTo("/todos/1", 1), { error: new Error("Failed") });
|
|
404
|
+
expect(doneOf(result.current.list.data, 1)).toBeTrue();
|
|
405
|
+
|
|
406
|
+
await setup.answer(await setup.lastCallTo("/todos/1", 2), { error: new Error("Failed") });
|
|
407
|
+
expect(doneOf(result.current.list.data, 1)).toBeFalse();
|
|
408
|
+
});
|
|
409
|
+
});
|
|
410
|
+
|
|
411
|
+
describe("when the list is infinite", () => {
|
|
412
|
+
it("should change and revert every loaded page with optimistic.all", async () => {
|
|
413
|
+
const setup = createSetup();
|
|
414
|
+
const getPages = setup.client.createRequest<{ response: Todo[]; queryParams: { page?: number } }>()({
|
|
415
|
+
endpoint: "/pages",
|
|
416
|
+
});
|
|
417
|
+
const remove = setup.client
|
|
418
|
+
.createRequest<{ response: null }>()({ endpoint: "/pages/:id", method: "DELETE" })
|
|
419
|
+
.setOptimistic(({ params }) => [
|
|
420
|
+
optimistic
|
|
421
|
+
.all(getPages)
|
|
422
|
+
.remove(params.id)
|
|
423
|
+
.rollback(({ data, previous }) => {
|
|
424
|
+
const index = previous.findIndex((item) => item.id === Number(params.id));
|
|
425
|
+
if (index === -1) {
|
|
426
|
+
return data;
|
|
427
|
+
}
|
|
428
|
+
const next = [...data];
|
|
429
|
+
next.splice(index, 0, previous[index]);
|
|
430
|
+
return next;
|
|
431
|
+
}),
|
|
432
|
+
]);
|
|
433
|
+
const { result } = renderHook(() => ({
|
|
434
|
+
list: useInfiniteFetch(getPages, { pagination: { page: "page" }, dependencyTracking: false }),
|
|
435
|
+
button: useSubmit(remove, { dependencyTracking: false }),
|
|
436
|
+
}));
|
|
437
|
+
await setup.answer(await setup.lastCallTo("/pages", 1), { data: [todo(1), todo(2)] });
|
|
438
|
+
await waitFor(() => expect(result.current.list.items).toHaveLength(2));
|
|
439
|
+
let nextPage: Promise<unknown> = Promise.resolve();
|
|
440
|
+
act(() => {
|
|
441
|
+
nextPage = result.current.list.fetchNextPage();
|
|
442
|
+
});
|
|
443
|
+
await setup.answer(await setup.lastCallTo("/pages", 2), { data: [todo(3), todo(4)] });
|
|
444
|
+
await act(() => nextPage);
|
|
445
|
+
|
|
446
|
+
act(() => {
|
|
447
|
+
result.current.button.submit({ params: { id: 3 } });
|
|
448
|
+
});
|
|
449
|
+
await waitFor(() => expect(result.current.list.items.map((item) => item.id)).toStrictEqual([1, 2, 4]));
|
|
450
|
+
|
|
451
|
+
await setup.answer(await setup.lastCallTo("/pages/3", 1), { error: new Error("Failed") });
|
|
452
|
+
await waitFor(() => expect(result.current.list.items.map((item) => item.id)).toStrictEqual([1, 2, 3, 4]));
|
|
453
|
+
});
|
|
454
|
+
});
|
|
455
|
+
});
|
|
@@ -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
|
|