@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.
Files changed (98) hide show
  1. package/__tests__/features/helpers/use-tracked-state/use-tacked-state.actions.spec.ts +1 -1
  2. package/__tests__/features/helpers/use-tracked-state/use-tracked-state.keys.spec.ts +294 -0
  3. package/__tests__/features/helpers/utils.spec.ts +127 -0
  4. package/__tests__/features/provider/provider.config.spec.tsx +172 -0
  5. package/__tests__/features/use-app-manager/use-app-manager.events.spec.tsx +497 -0
  6. package/__tests__/features/use-cache/use-cache.state.spec.tsx +326 -0
  7. package/__tests__/features/use-emitter/use-emitter.lifecycle.spec.tsx +417 -0
  8. package/__tests__/features/use-fetch/use-fetch.bounce-timers.spec.ts +199 -0
  9. package/__tests__/features/use-fetch/use-fetch.cache-events.spec.ts +212 -0
  10. package/__tests__/features/use-fetch/use-fetch.callbacks.spec.tsx +359 -0
  11. package/__tests__/features/use-fetch/use-fetch.hydration.spec.tsx +126 -0
  12. package/__tests__/features/use-fetch/use-fetch.infinite.spec.ts +146 -0
  13. package/__tests__/features/use-fetch/use-fetch.initial-state.spec.ts +340 -0
  14. package/__tests__/features/use-fetch/use-fetch.keys.spec.tsx +559 -0
  15. package/__tests__/features/use-fetch/use-fetch.lifecycle.spec.ts +348 -0
  16. package/__tests__/features/use-fetch/use-fetch.mounting.spec.tsx +411 -0
  17. package/__tests__/features/use-fetch/use-fetch.pagination.spec.ts +177 -0
  18. package/__tests__/features/use-fetch/use-fetch.refresh-interval.spec.ts +355 -0
  19. package/__tests__/features/use-fetch/use-fetch.response-order.spec.ts +105 -0
  20. package/__tests__/features/use-fetch/use-fetch.retry.spec.ts +235 -0
  21. package/__tests__/features/use-fetch/use-fetch.return-types.spec.ts +186 -0
  22. package/__tests__/features/use-fetch/use-fetch.scope.spec.ts +333 -0
  23. package/__tests__/features/use-fetch/use-fetch.ssr.spec.tsx +195 -0
  24. package/__tests__/features/use-fetch/use-fetch.suspense-edge.spec.tsx +391 -0
  25. package/__tests__/features/use-fetch/use-fetch.throwing-callbacks.spec.tsx +112 -0
  26. package/__tests__/features/use-fetch/use-fetch.tracking.spec.tsx +364 -0
  27. package/__tests__/features/use-fetch/use-fetch.window-events.spec.ts +300 -0
  28. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.parity.spec.tsx +1027 -0
  29. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.resubscribe.spec.tsx +267 -0
  30. package/__tests__/features/use-infinite-fetch/use-infinite-fetch.typescript.spec.ts +64 -1
  31. package/__tests__/features/use-is-fetching/use-is-fetching.lifecycle.spec.tsx +301 -0
  32. package/__tests__/features/use-listener/use-listener.lifecycle.spec.tsx +507 -0
  33. package/__tests__/features/use-listener/use-listener.ssr.spec.tsx +89 -0
  34. package/__tests__/features/use-queue/use-queue.controls.spec.tsx +593 -0
  35. package/__tests__/features/use-queue/use-queue.list.spec.tsx +560 -0
  36. package/__tests__/features/use-queue/use-queue.progress.spec.tsx +650 -0
  37. package/__tests__/features/use-submit/use-submit.abort.spec.tsx +270 -0
  38. package/__tests__/features/use-submit/use-submit.actions.spec.tsx +446 -0
  39. package/__tests__/features/use-submit/use-submit.arguments.spec.tsx +732 -0
  40. package/__tests__/features/use-submit/use-submit.bounce.spec.tsx +644 -0
  41. package/__tests__/features/use-submit/use-submit.callbacks.spec.tsx +860 -0
  42. package/__tests__/features/use-submit/use-submit.chaining.spec.tsx +167 -0
  43. package/__tests__/features/use-submit/use-submit.double-submit.spec.tsx +552 -0
  44. package/__tests__/features/use-submit/use-submit.offline.spec.tsx +285 -0
  45. package/__tests__/features/use-submit/use-submit.optimistic-cache.spec.tsx +619 -0
  46. package/__tests__/features/use-submit/use-submit.optimistic-helpers.spec.tsx +455 -0
  47. package/__tests__/features/use-submit/use-submit.optimistic-settlement.spec.ts +6 -0
  48. package/__tests__/features/use-submit/use-submit.optimistic.spec.ts +5 -1
  49. package/__tests__/features/use-submit/use-submit.state.spec.tsx +1025 -0
  50. package/__tests__/features/use-submit/use-submit.submit-types.spec.ts +194 -0
  51. package/__tests__/features/use-submit/use-submit.submitting.spec.tsx +180 -0
  52. package/__tests__/utils/gate.utils.ts +103 -0
  53. package/__tests__/utils/gated-client.utils.ts +158 -0
  54. package/__tests__/utils/helpers.utils.ts +19 -0
  55. package/dist/helpers/use-request-events/use-request-events.hooks.d.ts.map +1 -1
  56. package/dist/helpers/use-request-events/use-request-events.types.d.ts +1 -1
  57. package/dist/helpers/use-request-events/use-request-events.types.d.ts.map +1 -1
  58. package/dist/helpers/use-tracked-state/use-tracked-state.hooks.d.ts.map +1 -1
  59. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts +8 -0
  60. package/dist/helpers/use-tracked-state/use-tracked-state.utils.d.ts.map +1 -1
  61. package/dist/hooks/use-cache/use-cache.hooks.d.ts.map +1 -1
  62. package/dist/hooks/use-fetch/use-fetch.hooks.d.ts.map +1 -1
  63. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.hooks.d.ts.map +1 -1
  64. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts +3 -0
  65. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.store.d.ts.map +1 -1
  66. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts +5 -3
  67. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.types.d.ts.map +1 -1
  68. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts +11 -1
  69. package/dist/hooks/use-infinite-fetch/use-infinite-fetch.utils.d.ts.map +1 -1
  70. package/dist/hooks/use-listener/use-listener.hooks.d.ts.map +1 -1
  71. package/dist/hooks/use-queue/use-queue.hooks.d.ts.map +1 -1
  72. package/dist/hooks/use-submit/use-submit.constants.d.ts +1 -1
  73. package/dist/hooks/use-submit/use-submit.constants.d.ts.map +1 -1
  74. package/dist/hooks/use-submit/use-submit.hooks.d.ts.map +1 -1
  75. package/dist/hooks/use-submit/use-submit.types.d.ts +6 -1
  76. package/dist/hooks/use-submit/use-submit.types.d.ts.map +1 -1
  77. package/dist/index.mjs +633 -346
  78. package/dist/index.mjs.map +1 -1
  79. package/dist/provider/provider.d.ts.map +1 -1
  80. package/package.json +1 -1
  81. package/src/helpers/use-request-events/use-request-events.hooks.ts +141 -28
  82. package/src/helpers/use-request-events/use-request-events.types.ts +1 -1
  83. package/src/helpers/use-tracked-state/use-tracked-state.hooks.ts +148 -101
  84. package/src/helpers/use-tracked-state/use-tracked-state.utils.ts +26 -5
  85. package/src/hooks/use-cache/use-cache.hooks.ts +20 -5
  86. package/src/hooks/use-fetch/use-fetch.hooks.ts +194 -113
  87. package/src/hooks/use-infinite-fetch/use-infinite-fetch.hooks.ts +55 -26
  88. package/src/hooks/use-infinite-fetch/use-infinite-fetch.store.ts +35 -29
  89. package/src/hooks/use-infinite-fetch/use-infinite-fetch.types.ts +5 -3
  90. package/src/hooks/use-infinite-fetch/use-infinite-fetch.utils.ts +25 -1
  91. package/src/hooks/use-listener/use-listener.hooks.ts +2 -1
  92. package/src/hooks/use-queue/use-queue.hooks.ts +85 -60
  93. package/src/hooks/use-submit/use-submit.constants.ts +3 -1
  94. package/src/hooks/use-submit/use-submit.hooks.ts +167 -53
  95. package/src/hooks/use-submit/use-submit.types.ts +6 -0
  96. package/src/provider/provider.tsx +9 -1
  97. package/__tests__/features/use-fetch/use-fetch.pagination.ts +0 -36
  98. package/__tests__/features/use-fetch/use-fetch.retry.ts +0 -38
@@ -0,0 +1,194 @@
1
+ import type { ExtractAdapterResolvedType, RequestSendType } from "@hyper-fetch/core";
2
+ import { Client } from "@hyper-fetch/core";
3
+ import type { UseSubmitReturnType } from "hooks/use-submit";
4
+ import { useSubmit } from "hooks/use-submit";
5
+ import { expectTypeOf } from "vitest";
6
+
7
+ type User = { id: number; name: string };
8
+ type ApiError = { code: string; message: string };
9
+
10
+ const client = new Client({ url: "http://localhost:3000" });
11
+
12
+ const createUser = client.createRequest<{ response: User; payload: { name: string }; error: ApiError }>()({
13
+ method: "POST",
14
+ endpoint: "/users",
15
+ });
16
+
17
+ const renameUser = client.createRequest<{ response: User; payload: { name: string } }>()({
18
+ method: "PATCH",
19
+ endpoint: "/teams/:teamId/users/:userId",
20
+ });
21
+
22
+ const deleteUser = client.createRequest<{ response: null }>()({
23
+ method: "DELETE",
24
+ endpoint: "/users/:userId",
25
+ });
26
+
27
+ const importUsers = client.createRequest<{ response: User[]; queryParams: { dryRun: boolean } }>()({
28
+ method: "POST",
29
+ endpoint: "/users/import",
30
+ });
31
+
32
+ const pingServer = client.createRequest<{ response: { ok: boolean } }>()({
33
+ method: "POST",
34
+ endpoint: "/ping",
35
+ });
36
+
37
+ /** Only the types matter in this file - the submit functions are never called */
38
+ const getSubmit = <Request extends Parameters<typeof useSubmit>[0]>() =>
39
+ null as unknown as UseSubmitReturnType<Request>["submit"];
40
+
41
+ describe("useSubmit [ Submit types ]", () => {
42
+ describe("submit arguments", () => {
43
+ it("should require the payload", () => {
44
+ const submit = getSubmit<typeof createUser>();
45
+
46
+ expectTypeOf(submit).parameter(0).toHaveProperty("payload").toEqualTypeOf<{ name: string }>();
47
+ // @ts-expect-error - payload is required
48
+ expectTypeOf(submit).toBeCallableWith();
49
+ // @ts-expect-error - payload is required
50
+ expectTypeOf(submit).toBeCallableWith({});
51
+ expectTypeOf(submit).toBeCallableWith({ payload: { name: "Maciej" } });
52
+ });
53
+ it("should reject a payload of a wrong shape", () => {
54
+ const submit = getSubmit<typeof createUser>();
55
+
56
+ // @ts-expect-error - name has to be a string
57
+ expectTypeOf(submit).toBeCallableWith({ payload: { name: 1 } });
58
+ // @ts-expect-error - name is missing
59
+ expectTypeOf(submit).toBeCallableWith({ payload: {} });
60
+ });
61
+ it("should require the params of the endpoint", () => {
62
+ const submit = getSubmit<typeof deleteUser>();
63
+
64
+ expectTypeOf(submit).toBeCallableWith({ params: { userId: 1 } });
65
+ expectTypeOf(submit).toBeCallableWith({ params: { userId: "1" } });
66
+ // @ts-expect-error - params are required
67
+ expectTypeOf(submit).toBeCallableWith();
68
+ // @ts-expect-error - userId is missing
69
+ expectTypeOf(submit).toBeCallableWith({ params: {} });
70
+ });
71
+ it("should require every param together with the payload", () => {
72
+ const submit = getSubmit<typeof renameUser>();
73
+
74
+ expectTypeOf(submit).toBeCallableWith({ payload: { name: "Maciej" }, params: { teamId: 1, userId: 2 } });
75
+ // @ts-expect-error - params are missing
76
+ expectTypeOf(submit).toBeCallableWith({ payload: { name: "Maciej" } });
77
+ // @ts-expect-error - payload is missing
78
+ expectTypeOf(submit).toBeCallableWith({ params: { teamId: 1, userId: 2 } });
79
+ // @ts-expect-error - teamId is missing
80
+ expectTypeOf(submit).toBeCallableWith({ payload: { name: "Maciej" }, params: { userId: 2 } });
81
+ });
82
+ it("should require the declared query params", () => {
83
+ const submit = getSubmit<typeof importUsers>();
84
+
85
+ expectTypeOf(submit).toBeCallableWith({ queryParams: { dryRun: true } });
86
+ // @ts-expect-error - query params are required
87
+ expectTypeOf(submit).toBeCallableWith();
88
+ // @ts-expect-error - dryRun has to be a boolean
89
+ expectTypeOf(submit).toBeCallableWith({ queryParams: { dryRun: "yes" } });
90
+ });
91
+ it("should not require any argument when the request needs no data", () => {
92
+ const submit = getSubmit<typeof pingServer>();
93
+
94
+ expectTypeOf(submit).toBeCallableWith();
95
+ expectTypeOf(submit).toBeCallableWith({});
96
+ });
97
+ it("should not require the data that is already set on the request", () => {
98
+ const withParams = renameUser.setParams({ teamId: 1, userId: 2 });
99
+ const withAll = withParams.setPayload({ name: "Maciej" });
100
+ const submitWithParams = getSubmit<typeof withParams>();
101
+ const submitWithAll = getSubmit<typeof withAll>();
102
+
103
+ expectTypeOf(submitWithParams).toBeCallableWith({ payload: { name: "Maciej" } });
104
+ // @ts-expect-error - payload is still required
105
+ expectTypeOf(submitWithParams).toBeCallableWith();
106
+ expectTypeOf(submitWithAll).toBeCallableWith();
107
+ });
108
+ it("should accept the lifecycle callbacks next to the data", () => {
109
+ const submit = getSubmit<typeof createUser>();
110
+
111
+ expectTypeOf(submit).toBeCallableWith({
112
+ payload: { name: "Maciej" },
113
+ onBeforeSent: ({ requestId }) => requestId,
114
+ onResponse: ({ response }) => response.data,
115
+ });
116
+ });
117
+ it("should have the same signature as the send method of the request", () => {
118
+ expectTypeOf<UseSubmitReturnType<typeof createUser>["submit"]>().toEqualTypeOf<
119
+ RequestSendType<typeof createUser>
120
+ >();
121
+ expectTypeOf<UseSubmitReturnType<typeof deleteUser>["submit"]>().toEqualTypeOf<
122
+ RequestSendType<typeof deleteUser>
123
+ >();
124
+ });
125
+ });
126
+
127
+ describe("submit result", () => {
128
+ it("should return a promise of the response", () => {
129
+ const submit = getSubmit<typeof createUser>();
130
+
131
+ expectTypeOf(submit).returns.toEqualTypeOf<Promise<ExtractAdapterResolvedType<typeof createUser>>>();
132
+ });
133
+ it("should type the data and the error of the response", () => {
134
+ const submit = getSubmit<typeof createUser>();
135
+ type Result = Awaited<ReturnType<typeof submit>>;
136
+
137
+ expectTypeOf<Result["data"]>().toEqualTypeOf<User | null>();
138
+ expectTypeOf<Result["error"]>().toEqualTypeOf<ApiError | Error | null>();
139
+ expectTypeOf<Result["success"]>().toEqualTypeOf<boolean>();
140
+ expectTypeOf<Result["requestTimestamp"]>().toEqualTypeOf<number>();
141
+ expectTypeOf<Result["responseTimestamp"]>().toEqualTypeOf<number>();
142
+ });
143
+ it("should keep the full response in the result when the hook selects the data", () => {
144
+ const useSelected = () => useSubmit(createUser, { select: (user) => user.name });
145
+ type Selected = ReturnType<typeof useSelected>;
146
+
147
+ expectTypeOf<Selected["data"]>().toEqualTypeOf<string | null>();
148
+ expectTypeOf<Awaited<ReturnType<Selected["submit"]>>["data"]>().toEqualTypeOf<User | null>();
149
+ });
150
+ });
151
+
152
+ describe("returned state", () => {
153
+ type Result = UseSubmitReturnType<typeof createUser>;
154
+
155
+ it("should type the state values", () => {
156
+ expectTypeOf<Result["data"]>().toEqualTypeOf<User | null>();
157
+ expectTypeOf<Result["error"]>().toEqualTypeOf<ApiError | Error | null>();
158
+ expectTypeOf<Result["submitting"]>().toEqualTypeOf<boolean>();
159
+ expectTypeOf<Result["success"]>().toEqualTypeOf<boolean>();
160
+ expectTypeOf<Result["retries"]>().toEqualTypeOf<number>();
161
+ expectTypeOf<Result["requestTimestamp"]>().toEqualTypeOf<Date | null>();
162
+ expectTypeOf<Result["responseTimestamp"]>().toEqualTypeOf<Date | null>();
163
+ });
164
+ it("should expose submitting instead of loading", () => {
165
+ expectTypeOf<Result>().toHaveProperty("submitting");
166
+ expectTypeOf<Result>().not.toHaveProperty("loading");
167
+ });
168
+ it("should type the helpers", () => {
169
+ expectTypeOf<Result["abort"]>().toEqualTypeOf<() => void>();
170
+ expectTypeOf<Result["refetch"]>().toEqualTypeOf<() => void>();
171
+ expectTypeOf<Result["bounce"]>().toEqualTypeOf<{ active: boolean; reset: () => void }>();
172
+ });
173
+ it("should pass a single typed object to the callbacks", () => {
174
+ type SuccessParams = Parameters<Parameters<Result["onSubmitSuccess"]>[0]>;
175
+ type ErrorParams = Parameters<Parameters<Result["onSubmitError"]>[0]>;
176
+ type FinishedParams = Parameters<Parameters<Result["onSubmitFinished"]>[0]>;
177
+
178
+ expectTypeOf<SuccessParams["length"]>().toEqualTypeOf<1>();
179
+ expectTypeOf<SuccessParams[0]["response"]["data"]>().toEqualTypeOf<User>();
180
+ expectTypeOf<SuccessParams[0]["requestId"]>().toEqualTypeOf<string>();
181
+ expectTypeOf<ErrorParams[0]["response"]["error"]>().toEqualTypeOf<ApiError | Error>();
182
+ expectTypeOf<ErrorParams[0]["response"]["data"]>().toEqualTypeOf<null>();
183
+ expectTypeOf<FinishedParams[0]["response"]["data"]>().toEqualTypeOf<User | null>();
184
+ expectTypeOf<FinishedParams[0]["details"]["willRetry"]>().toEqualTypeOf<boolean>();
185
+ });
186
+ it("should type the mutation context of an optimistic request", () => {
187
+ const optimistic = createUser.setOptimistic(() => ({ context: { previous: [] as User[] } }));
188
+ type OptimisticResult = UseSubmitReturnType<typeof optimistic>;
189
+ type AbortParams = Parameters<Parameters<OptimisticResult["onSubmitAbort"]>[0]>[0];
190
+
191
+ expectTypeOf<AbortParams["mutationContext"]>().toEqualTypeOf<{ previous: User[] } | undefined>();
192
+ });
193
+ });
194
+ });
@@ -0,0 +1,180 @@
1
+ import { act, renderHook, waitFor } from "@testing-library/react";
2
+ import { useSubmit } from "hooks/use-submit";
3
+ import { StrictMode } from "react";
4
+
5
+ import { createGatedClient } from "../../utils/gated-client.utils";
6
+
7
+ type User = { id: number; name: string };
8
+
9
+ const setup = (options?: { queued?: boolean }) => {
10
+ const gated = createGatedClient();
11
+ const request = gated.client.createRequest<{ response: User; payload: { name: string } }>()({
12
+ endpoint: "/users",
13
+ method: "POST",
14
+ queued: options?.queued ?? false,
15
+ deduplicate: false,
16
+ });
17
+ return { ...gated, request };
18
+ };
19
+
20
+ /**
21
+ * One hook can have several requests on the way: queued one after another, or sent with different params (and so
22
+ * different keys). `submitting` is true from the first submit until the last of them is done.
23
+ */
24
+ describe("useSubmit [ Submitting ]", () => {
25
+ /** Renders the hook and records every value of `submitting` that a component would see */
26
+ const renderWithHistory = (request: Parameters<typeof useSubmit>[0], wrapper?: typeof StrictMode) => {
27
+ const history: boolean[] = [];
28
+ const view = renderHook(
29
+ () => {
30
+ const submit = useSubmit(request, { dependencyTracking: false });
31
+ if (history.at(-1) !== submit.submitting) {
32
+ history.push(submit.submitting);
33
+ }
34
+ return submit;
35
+ },
36
+ { wrapper },
37
+ );
38
+ return { ...view, history };
39
+ };
40
+
41
+ describe("when the requests are queued", () => {
42
+ it.each([
43
+ ["a component", undefined],
44
+ ["a component in StrictMode", StrictMode],
45
+ ])("should stay submitting between the requests for %s", async (_name, wrapper) => {
46
+ const { request, waitForCall } = setup({ queued: true });
47
+ const { result, history } = renderWithHistory(request, wrapper);
48
+ let promises: Promise<unknown>[] = [];
49
+ act(() => {
50
+ promises = ["First", "Second", "Third"].map((name) => result.current.submit({ payload: { name } }));
51
+ });
52
+
53
+ for (let index = 0; index < 3; index += 1) {
54
+ // eslint-disable-next-line no-await-in-loop
55
+ const call = await waitForCall(index);
56
+ // eslint-disable-next-line no-await-in-loop
57
+ await act(async () => {
58
+ call.succeed({ id: index, name: "User" });
59
+ await promises[index];
60
+ });
61
+ }
62
+ await waitFor(() => {
63
+ expect(result.current.submitting).toBeFalse();
64
+ });
65
+
66
+ expect(history).toStrictEqual([false, true, false]);
67
+ });
68
+
69
+ it("should stay submitting when one of the requests fails", async () => {
70
+ const { request, waitForCall } = setup({ queued: true });
71
+ const { result, history } = renderWithHistory(request);
72
+ let promises: Promise<unknown>[] = [];
73
+ act(() => {
74
+ promises = ["First", "Second"].map((name) => result.current.submit({ payload: { name } }));
75
+ });
76
+
77
+ const first = await waitForCall(0);
78
+ await act(async () => {
79
+ first.fail({ message: "Failed" }, 400);
80
+ await promises[0];
81
+ });
82
+ expect(result.current.submitting).toBeTrue();
83
+
84
+ const second = await waitForCall(1);
85
+ await act(async () => {
86
+ second.succeed({ id: 2, name: "Second" });
87
+ await promises[1];
88
+ });
89
+ await waitFor(() => {
90
+ expect(result.current.submitting).toBeFalse();
91
+ });
92
+
93
+ expect(history).toStrictEqual([false, true, false]);
94
+ expect(result.current.data).toStrictEqual({ id: 2, name: "Second" });
95
+ });
96
+
97
+ it("should stop submitting when the remaining requests are aborted", async () => {
98
+ const { request, waitForCall } = setup({ queued: true });
99
+ const { result } = renderWithHistory(request);
100
+ let promises: Promise<unknown>[] = [];
101
+ act(() => {
102
+ promises = ["First", "Second"].map((name) => result.current.submit({ payload: { name } }));
103
+ });
104
+ const first = await waitForCall(0);
105
+ await act(async () => {
106
+ first.succeed({ id: 1, name: "First" });
107
+ await promises[0];
108
+ });
109
+ await waitForCall(1);
110
+
111
+ await act(async () => {
112
+ result.current.abort();
113
+ await promises[1];
114
+ });
115
+
116
+ await waitFor(() => {
117
+ expect(result.current.submitting).toBeFalse();
118
+ });
119
+ });
120
+ });
121
+
122
+ describe("when the requests have different keys", () => {
123
+ it("should stay submitting until every one of them is done", async () => {
124
+ const { client, waitForCalls } = setup();
125
+ const request = client.createRequest<{ response: User }>()({ endpoint: "/users/:userId", method: "DELETE" });
126
+ const { result, history } = renderWithHistory(request as Parameters<typeof useSubmit>[0]);
127
+ let promises: Promise<unknown>[] = [];
128
+ act(() => {
129
+ promises = [1, 2].map((userId) => result.current.submit({ params: { userId } } as never));
130
+ });
131
+ const calls = await waitForCalls(2);
132
+
133
+ await act(async () => {
134
+ calls[1].succeed({ id: 2, name: "Second" });
135
+ await promises[1];
136
+ });
137
+ expect(client.submitDispatcher.getAllRunningRequests()).toHaveLength(1);
138
+ expect(result.current.submitting).toBeTrue();
139
+
140
+ await act(async () => {
141
+ calls[0].succeed({ id: 1, name: "First" });
142
+ await promises[0];
143
+ });
144
+ await waitFor(() => {
145
+ expect(result.current.submitting).toBeFalse();
146
+ });
147
+
148
+ expect(history).toStrictEqual([false, true, false]);
149
+ });
150
+ });
151
+
152
+ describe("when there is a single request", () => {
153
+ it.each([
154
+ ["succeeds", true],
155
+ ["fails", false],
156
+ ])("should stop submitting when it %s", async (_name, success) => {
157
+ const { request, waitForCall } = setup();
158
+ const { result, history } = renderWithHistory(request);
159
+ let promise: Promise<unknown> = Promise.resolve();
160
+ act(() => {
161
+ promise = result.current.submit({ payload: { name: "Maciej" } });
162
+ });
163
+ const call = await waitForCall(0);
164
+
165
+ await act(async () => {
166
+ if (success) {
167
+ call.succeed({ id: 1, name: "Maciej" });
168
+ } else {
169
+ call.fail({ message: "Failed" }, 400);
170
+ }
171
+ await promise;
172
+ });
173
+ await waitFor(() => {
174
+ expect(result.current.submitting).toBeFalse();
175
+ });
176
+
177
+ expect(history).toStrictEqual([false, true, false]);
178
+ });
179
+ });
180
+ });
@@ -0,0 +1,103 @@
1
+ import type { ExtractResponseType, RequestInstance } from "@hyper-fetch/core";
2
+ import { act } from "@testing-library/react";
3
+
4
+ export type GatedCall<Response = any> = {
5
+ /** Request instance received by the adapter */
6
+ request: RequestInstance;
7
+ requestId: string;
8
+ /** Resolve the call with a success response */
9
+ succeed: (data: Response, status?: number) => void;
10
+ /** Resolve the call with an error response */
11
+ fail: (error?: Error, status?: number) => void;
12
+ };
13
+
14
+ /**
15
+ * Attaches a mock that keeps every call pending until the test decides how it ends.
16
+ * No network and no default delays are involved - the order of responses is set by the test, not by timing.
17
+ * The mock is shared with the clones of the request (setParams, setQueryParams etc.).
18
+ */
19
+ export const gateRequest = <T extends RequestInstance>(request: T) => {
20
+ const calls: GatedCall<ExtractResponseType<T>>[] = [];
21
+
22
+ request.setMock(
23
+ ({ request: sentRequest, requestId }: { request: RequestInstance; requestId: string }) => {
24
+ return new Promise<any>((resolve) => {
25
+ calls.push({
26
+ request: sentRequest,
27
+ requestId,
28
+ succeed: (data, status = 200) => resolve({ data, status }),
29
+ fail: (error = new Error("Gated error"), status = 400) => resolve({ error, status, success: false }),
30
+ });
31
+ });
32
+ },
33
+ { requestTime: 0, responseTime: 0 },
34
+ );
35
+
36
+ return calls;
37
+ };
38
+
39
+ /**
40
+ * Time needed by the mocker to pass the upload and download phases once the gate is opened
41
+ */
42
+ export const GATE_SETTLE_TIME = 50;
43
+
44
+ /**
45
+ * Moves the fake clock forward inside of act(), flushing the promises between the timers.
46
+ * Requires `vi.useFakeTimers()`.
47
+ */
48
+ export const advance = async (time = 0) => {
49
+ await act(async () => {
50
+ await vi.advanceTimersByTimeAsync(time);
51
+ });
52
+ };
53
+
54
+ /**
55
+ * Lets the response of opened gates travel through the mocker, dispatcher and cache into the hooks.
56
+ */
57
+ export const settle = async () => {
58
+ await advance(GATE_SETTLE_TIME);
59
+ };
60
+
61
+ /**
62
+ * Saves a success response in the cache, the same way the dispatcher does it.
63
+ */
64
+ export const setCacheResponse = <T extends RequestInstance>(
65
+ request: T,
66
+ data: ExtractResponseType<T>,
67
+ timestamp: number = Date.now(),
68
+ ) => {
69
+ const response = {
70
+ data,
71
+ error: null,
72
+ status: 200,
73
+ success: true,
74
+ extra: request.client.adapter.defaultExtra,
75
+ requestTimestamp: timestamp,
76
+ responseTimestamp: timestamp,
77
+ addedTimestamp: timestamp,
78
+ triggerTimestamp: timestamp,
79
+ retries: 0,
80
+ isCanceled: false,
81
+ isOffline: false,
82
+ willRetry: false,
83
+ };
84
+ request.client.cache.set(request, response as any);
85
+ };
86
+
87
+ /**
88
+ * Number of listeners registered on the client emitters - used to prove that hooks clean up after themselves.
89
+ */
90
+ export const countListeners = (client: RequestInstance["client"]) => {
91
+ const count = (emitter: {
92
+ eventNames: () => (string | symbol)[];
93
+ listenerCount: (name: string | symbol) => number;
94
+ }) => emitter.eventNames().reduce((sum, name) => sum + emitter.listenerCount(name), 0);
95
+
96
+ return {
97
+ requestManager: count(client.requestManager.emitter),
98
+ cache: count(client.cache.emitter),
99
+ appManager: count(client.appManager.emitter),
100
+ fetchDispatcher: count(client.fetchDispatcher.emitter),
101
+ submitDispatcher: count(client.submitDispatcher.emitter),
102
+ };
103
+ };
@@ -0,0 +1,158 @@
1
+ import type { RequestInstance } from "@hyper-fetch/core";
2
+ import { Client } from "@hyper-fetch/core";
3
+ import { act, waitFor } from "@testing-library/react";
4
+
5
+ /**
6
+ * Deterministic test transport.
7
+ *
8
+ * Every request sent through the gated client stays "in flight" until the test settles it, so there are no mock
9
+ * delays and nothing depends on how fast the machine is. Each attempt (first try and every retry) is a separate call.
10
+ */
11
+ export type GatedCall = {
12
+ /** Position of the call in the order requests reached the adapter (0-based) */
13
+ index: number;
14
+ requestId: string;
15
+ request: RequestInstance;
16
+ payload: unknown;
17
+ /** True once the request got aborted by the library */
18
+ aborted: boolean;
19
+ /** True once the call was answered or aborted */
20
+ settled: boolean;
21
+ /** Answer the request with a successful response */
22
+ succeed: (data?: unknown, status?: number) => void;
23
+ /** Answer the request with an error response */
24
+ fail: (error?: unknown, status?: number) => void;
25
+ /** Report upload progress */
26
+ upload: (loaded: number, total: number) => void;
27
+ /** Report download progress */
28
+ download: (loaded: number, total: number) => void;
29
+ };
30
+
31
+ const gatedExtra = { headers: { "content-type": "application/json" } };
32
+
33
+ export const createGatedClient = (options?: { url?: string }) => {
34
+ const calls: GatedCall[] = [];
35
+
36
+ const client = new Client({ url: options?.url ?? "http://gated-client" });
37
+
38
+ client.adapter.setFetcher(
39
+ async ({
40
+ request,
41
+ requestId,
42
+ payload,
43
+ onBeforeRequest,
44
+ onRequestStart,
45
+ onRequestProgress,
46
+ onRequestEnd,
47
+ onResponseStart,
48
+ onResponseProgress,
49
+ onResponseEnd,
50
+ onSuccess,
51
+ onError,
52
+ createAbortListener,
53
+ }) => {
54
+ const call: GatedCall = {
55
+ index: calls.length,
56
+ requestId,
57
+ request,
58
+ payload,
59
+ aborted: false,
60
+ settled: false,
61
+ succeed: (data, status = 200) => {
62
+ if (call.settled) {
63
+ return;
64
+ }
65
+ call.settled = true;
66
+ onRequestEnd();
67
+ onResponseStart();
68
+ onResponseEnd();
69
+ onSuccess({ data: data === undefined ? { ok: true } : data, status, extra: gatedExtra } as never);
70
+ },
71
+ fail: (error, status = 400) => {
72
+ if (call.settled) {
73
+ return;
74
+ }
75
+ call.settled = true;
76
+ onRequestEnd();
77
+ onResponseStart();
78
+ onResponseEnd();
79
+ onError({
80
+ error: error === undefined ? { message: "Gated error" } : error,
81
+ status,
82
+ extra: gatedExtra,
83
+ } as never);
84
+ },
85
+ upload: (loaded, total) => {
86
+ if (call.settled) {
87
+ return;
88
+ }
89
+ onRequestProgress({ loaded, total });
90
+ },
91
+ download: (loaded, total) => {
92
+ if (call.settled) {
93
+ return;
94
+ }
95
+ onResponseProgress({ loaded, total });
96
+ },
97
+ };
98
+
99
+ createAbortListener({
100
+ status: 0,
101
+ extra: gatedExtra,
102
+ onAbort: () => {
103
+ call.aborted = true;
104
+ call.settled = true;
105
+ },
106
+ } as never);
107
+
108
+ calls.push(call);
109
+
110
+ if (!call.settled) {
111
+ onBeforeRequest();
112
+ onRequestStart();
113
+ }
114
+ },
115
+ );
116
+
117
+ /** Wait until the n-th call (0-based) reached the adapter and return it */
118
+ const waitForCall = async (index: number): Promise<GatedCall> => {
119
+ await waitFor(() => {
120
+ expect(calls.length).toBeGreaterThan(index);
121
+ });
122
+ return calls[index];
123
+ };
124
+
125
+ /** Wait until exactly `count` calls reached the adapter */
126
+ const waitForCalls = async (count: number): Promise<GatedCall[]> => {
127
+ await waitFor(() => {
128
+ expect(calls).toHaveLength(count);
129
+ });
130
+ return calls;
131
+ };
132
+
133
+ /** Calls that are still waiting for an answer */
134
+ const pending = () => calls.filter((call) => !call.settled);
135
+
136
+ return { client, calls, pending, waitForCall, waitForCalls, extra: gatedExtra };
137
+ };
138
+
139
+ /** Flush promise callbacks (and the effects they schedule) without waiting for real time to pass */
140
+ export const flushPromises = async (rounds = 5) => {
141
+ await act(async () => {
142
+ for (let i = 0; i < rounds; i += 1) {
143
+ // eslint-disable-next-line no-await-in-loop
144
+ await Promise.resolve();
145
+ }
146
+ });
147
+ };
148
+
149
+ /** Promise that the test resolves by hand */
150
+ export const createDeferred = <T = void>() => {
151
+ let resolve!: (value: T) => void;
152
+ let reject!: (reason?: unknown) => void;
153
+ const promise = new Promise<T>((res, rej) => {
154
+ resolve = res;
155
+ reject = rej;
156
+ });
157
+ return { promise, resolve, reject };
158
+ };
@@ -7,3 +7,22 @@ export const waitForRender = async (time = 10) => {
7
7
  await sleep(time);
8
8
  });
9
9
  };
10
+
11
+ /**
12
+ * Errors of the user code (callbacks, listeners, plugins) are thrown from a timer, outside of the request lifecycle.
13
+ * Collects them for the assertions; the listener stays until the timers scheduled by the test have run.
14
+ */
15
+ export const collectThrownErrors = () => {
16
+ const errors: unknown[] = [];
17
+ const handler = (error: unknown) => {
18
+ errors.push(error);
19
+ };
20
+ process.on("uncaughtException", handler);
21
+ onTestFinished(async () => {
22
+ await new Promise((resolve) => {
23
+ setTimeout(resolve, 0);
24
+ });
25
+ process.off("uncaughtException", handler);
26
+ });
27
+ return errors;
28
+ };
@@ -1 +1 @@
1
- {"version":3,"file":"use-request-events.hooks.d.ts","sourceRoot":"","sources":["../../../src/helpers/use-request-events/use-request-events.hooks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAGV,eAAe,EAQhB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,KAAK,EAOV,0BAA0B,EAC1B,yBAAyB,EAE1B,MAAM,SAAS,CAAC;AAIjB;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,GAAI,CAAC,SAAS,eAAe,EAAE,8EAOzD,yBAAyB,CAAC,CAAC,CAAC,KAAG,0BAA0B,CAAC,CAAC,CA6T7D,CAAC"}
1
+ {"version":3,"file":"use-request-events.hooks.d.ts","sourceRoot":"","sources":["../../../src/helpers/use-request-events/use-request-events.hooks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAGV,eAAe,EAShB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,KAAK,EAOV,0BAA0B,EAC1B,yBAAyB,EAE1B,MAAM,SAAS,CAAC;AAIjB;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,GAAI,CAAC,SAAS,eAAe,EAAE,8EAOzD,yBAAyB,CAAC,CAAC,CAAC,KAAG,0BAA0B,CAAC,CAAC,CA6a7D,CAAC"}
@@ -69,7 +69,7 @@ export type UseRequestEventsReturnType<T extends RequestInstance> = [
69
69
  export type CallbackParameters<Request extends RequestInstance, Resp> = {
70
70
  response: Resp;
71
71
  mutationContext: ExtractMutationContextType<Request> | undefined;
72
- } & Omit<RequestResponseEventType<Request>, "response">;
72
+ } & Omit<RequestResponseEventType<Request>, "response" | "mutationContext">;
73
73
  export type OnSuccessCallbackType<Request extends RequestInstance> = (params: CallbackParameters<Request, ResponseSuccessType<ExtractResponseType<Request>, ExtractAdapterType<Request>>>) => void | Promise<void>;
74
74
  export type OnErrorCallbackType<Request extends RequestInstance> = (params: CallbackParameters<Request, ResponseErrorType<ExtractErrorType<Request>, ExtractAdapterType<Request>>>) => void | Promise<void>;
75
75
  export type OnFinishedCallbackType<Request extends RequestInstance> = (params: CallbackParameters<Request, ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>>) => void | Promise<void>;