@hyper-fetch/core 7.5.2 → 7.5.3

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 (54) hide show
  1. package/__tests__/features/adapter/adapter.base.spec.ts +387 -0
  2. package/__tests__/features/adapter/adapter.bindings.spec.ts +1023 -0
  3. package/__tests__/features/adapter/adapter.browser.spec.ts +103 -0
  4. package/__tests__/features/adapter/adapter.server.spec.ts +177 -0
  5. package/__tests__/features/adapter/adapter.utils.spec.ts +165 -0
  6. package/__tests__/features/cache/cache.base.spec.ts +358 -0
  7. package/__tests__/features/cache/cache.events.spec.ts +215 -0
  8. package/__tests__/features/cache/cache.garbage-collector.spec.ts +172 -0
  9. package/__tests__/features/cache/cache.lazy-storage.spec.ts +129 -0
  10. package/__tests__/features/cache/cache.utils.spec.ts +119 -0
  11. package/__tests__/features/client/client.auth.spec.ts +125 -0
  12. package/__tests__/features/client/client.base.spec.ts +149 -0
  13. package/__tests__/features/client/client.hydration.spec.ts +171 -0
  14. package/__tests__/features/client/client.interceptor.spec.ts +225 -0
  15. package/__tests__/features/client/client.methods.spec.ts +188 -0
  16. package/__tests__/features/client/client.middleware.spec.ts +118 -0
  17. package/__tests__/features/client/client.utils.spec.ts +292 -0
  18. package/__tests__/features/dispatcher/dispatcher.base.spec.ts +123 -0
  19. package/__tests__/features/dispatcher/dispatcher.events.spec.ts +304 -0
  20. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +462 -0
  21. package/__tests__/features/dispatcher/dispatcher.requests.spec.ts +241 -0
  22. package/__tests__/features/dispatcher/dispatcher.utils.spec.ts +125 -0
  23. package/__tests__/features/managers/app/app.manager.base.spec.ts +235 -0
  24. package/__tests__/features/managers/app/app.manager.ssr.spec.ts +40 -0
  25. package/__tests__/features/managers/logger/logger.base.spec.ts +107 -0
  26. package/__tests__/features/managers/logger/logger.utils.spec.ts +100 -0
  27. package/__tests__/features/managers/request/request.manager.base.spec.ts +222 -0
  28. package/__tests__/features/managers/request/request.manager.events.spec.ts +280 -0
  29. package/__tests__/features/mocker/mocker.base.spec.ts +567 -0
  30. package/__tests__/features/plugin/plugin.base.spec.ts +255 -0
  31. package/__tests__/features/request/request.base.spec.ts +199 -0
  32. package/__tests__/features/request/request.cloning.spec.ts +47 -0
  33. package/__tests__/features/request/request.sending.spec.ts +272 -0
  34. package/__tests__/features/request/request.setters.spec.ts +157 -0
  35. package/__tests__/features/request/request.typescript.spec.ts +423 -0
  36. package/__tests__/features/request/request.utils.spec.ts +77 -0
  37. package/__tests__/features/sdk/sdk.base.spec.ts +130 -0
  38. package/__tests__/global.d.ts +1 -0
  39. package/__tests__/jest.setup.ts +13 -0
  40. package/__tests__/shared/callbacks.shared.ts +9 -0
  41. package/__tests__/shared/index.ts +2 -0
  42. package/__tests__/shared/progress.shared.ts +35 -0
  43. package/__tests__/tsconfig.json +13 -0
  44. package/__tests__/utils/adapter.utils.ts +38 -0
  45. package/__tests__/utils/cache.utils.ts +19 -0
  46. package/__tests__/utils/callbacks.utils.ts +47 -0
  47. package/__tests__/utils/dispatcher.utils.ts +6 -0
  48. package/__tests__/utils/index.ts +4 -0
  49. package/dist/index.js +12 -1
  50. package/dist/index.js.map +2 -2
  51. package/jest.config.ts +6 -0
  52. package/package.json +1 -1
  53. package/project.json +4 -0
  54. package/src/http-adapter/http-adapter.server.ts +15 -1
@@ -0,0 +1,172 @@
1
+ import { waitFor } from "@testing-library/dom";
2
+
3
+ import { CacheValueType } from "cache";
4
+ import { Client, Time, xhrExtra } from "index";
5
+ import { createCache, createLazyCacheAdapter } from "../../utils";
6
+
7
+ describe("Cache [ Garbage Collector ]", () => {
8
+ const cacheKey = "test";
9
+ const staleTime = 30000;
10
+ const version = "test";
11
+ const cacheTime = 10000;
12
+ const cacheData: CacheValueType = {
13
+ data: null,
14
+ error: null,
15
+ status: 200,
16
+ success: true,
17
+ extra: xhrExtra,
18
+ retries: 0,
19
+ requestTimestamp: +new Date(),
20
+ responseTimestamp: +new Date(),
21
+ addedTimestamp: +new Date(),
22
+ triggerTimestamp: +new Date(),
23
+ isCanceled: false,
24
+ isOffline: false,
25
+ staleTime,
26
+ version,
27
+ cacheTime,
28
+ cacheKey,
29
+ };
30
+
31
+ let client = new Client({ url: "shared-base-url" });
32
+ let request = client.createRequest()({ endpoint: "shared-endpoint", cacheKey, staleTime, cacheTime });
33
+ let cache = createCache(client, {
34
+ version,
35
+ });
36
+
37
+ beforeEach(async () => {
38
+ client = new Client({ url: "shared-base-url" });
39
+ request = client.createRequest()({ endpoint: "shared-endpoint", cacheKey, staleTime, cacheTime });
40
+ cache = createCache(client, {
41
+ version,
42
+ });
43
+ jest.resetAllMocks();
44
+ jest.clearAllMocks();
45
+
46
+ cacheData.requestTimestamp = +new Date();
47
+ cacheData.responseTimestamp = +new Date();
48
+ cacheData.addedTimestamp = +new Date();
49
+ cacheData.triggerTimestamp = +new Date();
50
+ });
51
+
52
+ describe("when garbage collector is triggered", () => {
53
+ it("should not schedule garbage collector for non existing key", async () => {
54
+ cache.scheduleGarbageCollector(cacheKey);
55
+ expect(Array.from(cache.garbageCollectors.keys())).toHaveLength(0);
56
+ });
57
+ it("should garbage collect data from sync storage", async () => {
58
+ cache.set(request.setCacheTime(10), cacheData);
59
+ await waitFor(() => {
60
+ expect(cache.get(cacheKey)).not.toBeDefined();
61
+ });
62
+ });
63
+ it("should garbage collect data from lazy storage", async () => {
64
+ cache.set(request, cacheData);
65
+ cache.scheduleGarbageCollector(request.cacheKey);
66
+
67
+ await waitFor(async () => {
68
+ expect(await cache.options?.lazyStorage?.get(cacheKey)).not.toBeDefined();
69
+ });
70
+ });
71
+ it("should schedule garbage collection on mount", async () => {
72
+ const storage = new Map().set("cacheKey", cacheData);
73
+
74
+ const cacheInstance = createCache(new Client({ url: "shared-base-url" }), {
75
+ storage,
76
+ version,
77
+ });
78
+ expect(Array.from(cacheInstance.garbageCollectors.keys())).toHaveLength(1);
79
+ });
80
+ it("should not schedule lazy storage garbage collection on mount", async () => {
81
+ const lazyStorage = new Map<string, CacheValueType>();
82
+ lazyStorage.set(cacheKey, cacheData);
83
+ const cacheInstance = createCache(client, {
84
+ lazyStorage: createLazyCacheAdapter(lazyStorage),
85
+ version,
86
+ });
87
+
88
+ await waitFor(() => {
89
+ expect(Array.from(cacheInstance.garbageCollectors.keys())).toHaveLength(0);
90
+ });
91
+ });
92
+ it("should schedule garbage collection when resource is added", async () => {
93
+ const spy = jest.spyOn(cache, "scheduleGarbageCollector");
94
+ cache.set(request, cacheData);
95
+ expect(spy).toHaveBeenCalledTimes(1);
96
+ });
97
+ it("should remove resource with not matching lazy version", async () => {
98
+ const lazyStorage = new Map<string, CacheValueType>();
99
+ const data = { ...cacheData, cacheTime: Time.MIN };
100
+ lazyStorage.set(request.cacheKey, data);
101
+ const newCache = createCache(client, {
102
+ lazyStorage: createLazyCacheAdapter(lazyStorage),
103
+ version: "new-clear-key",
104
+ });
105
+ const spy = jest.spyOn(lazyStorage, "delete");
106
+
107
+ // get to trigger garbage collector
108
+ newCache.get(request.cacheKey);
109
+
110
+ await waitFor(() => {
111
+ expect(spy).toHaveBeenCalledTimes(1);
112
+ expect(spy).toHaveBeenCalledWith(cacheKey);
113
+ });
114
+ });
115
+ it("should remove resource with not matching sync version", async () => {
116
+ const syncStorage = new Map<string, CacheValueType>();
117
+ const data = { ...cacheData, cacheTime: Time.MIN };
118
+ syncStorage.set(request.cacheKey, data);
119
+ const newCache = createCache(client, {
120
+ storage: syncStorage,
121
+ version: "new-clear-key",
122
+ });
123
+ const spy = jest.spyOn(syncStorage, "delete");
124
+
125
+ // get to trigger garbage collector
126
+ newCache.get(request.cacheKey);
127
+
128
+ await waitFor(() => {
129
+ expect(spy).toHaveBeenCalledTimes(1);
130
+ expect(spy).toHaveBeenCalledWith(cacheKey);
131
+ });
132
+ });
133
+ it("should not schedule garbage collection for Infinity", async () => {
134
+ const storage = new Map();
135
+ storage.set(cacheKey, { ...cacheData, cacheTime: Infinity });
136
+ const cacheInstance = createCache(client, {
137
+ storage,
138
+ version,
139
+ });
140
+
141
+ await waitFor(() => {
142
+ expect(Array.from(cacheInstance.garbageCollectors.keys())).toHaveLength(0);
143
+ });
144
+ });
145
+ it("should garbage collect when time left is less than zero", async () => {
146
+ const pastTimestamp = +new Date() - 20000; // 20 seconds ago
147
+ const staleData = {
148
+ ...cacheData,
149
+ responseTimestamp: pastTimestamp,
150
+ cacheTime: 10000, // 10 seconds
151
+ };
152
+
153
+ cache.set(request, staleData);
154
+
155
+ await waitFor(() => {
156
+ expect(cache.get(cacheKey)).not.toBeDefined();
157
+ });
158
+ });
159
+ it("should not schedule garbage collection for null", async () => {
160
+ const storage = new Map();
161
+ storage.set(cacheKey, { ...cacheData, cacheTime: null });
162
+ const cacheInstance = createCache(client, {
163
+ storage,
164
+ version,
165
+ });
166
+
167
+ await waitFor(() => {
168
+ expect(Array.from(cacheInstance.garbageCollectors.keys())).toHaveLength(0);
169
+ });
170
+ });
171
+ });
172
+ });
@@ -0,0 +1,129 @@
1
+ import { sleep } from "@hyper-fetch/testing";
2
+
3
+ import { CacheAsyncStorageType, CacheValueType } from "cache";
4
+ import { createCache, createLazyCacheAdapter } from "../../utils";
5
+ import { Client } from "client";
6
+ import { xhrExtra } from "http-adapter";
7
+
8
+ describe("Cache [ Lazy Storage ]", () => {
9
+ const staleTime = 10000;
10
+ const version = "test";
11
+ const cacheKey = "1";
12
+ const cacheData: CacheValueType = {
13
+ data: null,
14
+ error: null,
15
+ status: 200,
16
+ success: true,
17
+ extra: xhrExtra,
18
+ retries: 0,
19
+ addedTimestamp: +new Date(),
20
+ requestTimestamp: +new Date(),
21
+ responseTimestamp: +new Date(),
22
+ triggerTimestamp: +new Date(),
23
+ isCanceled: false,
24
+ isOffline: false,
25
+ staleTime,
26
+ version,
27
+ cacheTime: Infinity,
28
+ cacheKey,
29
+ };
30
+
31
+ const lazyStorage = new Map();
32
+ const spy = jest.fn();
33
+
34
+ let client = new Client({ url: "shared-base-url" });
35
+ let request = client.createRequest()({ endpoint: "shared-endpoint", cacheKey });
36
+ let cache = createCache(client, {
37
+ lazyStorage: createLazyCacheAdapter(lazyStorage),
38
+ version,
39
+ });
40
+
41
+ beforeEach(() => {
42
+ lazyStorage.clear();
43
+ client = new Client({ url: "shared-base-url" });
44
+ request = client.createRequest()({ endpoint: "shared-endpoint", cacheKey });
45
+ cache = createCache(client, {
46
+ lazyStorage: createLazyCacheAdapter(lazyStorage),
47
+ version,
48
+ });
49
+ jest.resetAllMocks();
50
+ });
51
+
52
+ describe("when using lazy storage", () => {
53
+ it("should not crash when lazy storage is not set", async () => {
54
+ const newClient = new Client({ url: "shared-base-url" });
55
+
56
+ await expect(newClient.cache.getLazyKeys()).resolves.not.toThrow();
57
+ await expect(newClient.cache.getAllKeys()).resolves.not.toThrow();
58
+ });
59
+ });
60
+ describe("when using lazy storage", () => {
61
+ it("should new data to lazy storage", async () => {
62
+ cache.events.onDataByKey(cacheKey, spy);
63
+ await cache.set(request, cacheData);
64
+ await sleep(10);
65
+ const data = cache.get(cacheKey);
66
+ await sleep(50);
67
+ expect(data).toBeDefined();
68
+ expect(spy).toHaveBeenCalledTimes(1);
69
+ });
70
+ it("should lazy load data", async () => {
71
+ await cache.options?.lazyStorage?.set(cacheKey, cacheData);
72
+ cache.events.onDataByKey(cacheKey, spy);
73
+ const data = cache.get(cacheKey);
74
+ await sleep(50);
75
+ expect(data).not.toBeDefined();
76
+ expect(spy).toHaveBeenCalledTimes(1);
77
+ });
78
+ it("should not emit stale data", async () => {
79
+ await cache.options?.lazyStorage?.set(cacheKey, { ...cacheData, responseTimestamp: +new Date() - staleTime });
80
+ cache.events.onDataByKey(cacheKey, spy);
81
+ const data = cache.get(cacheKey);
82
+ await sleep(50);
83
+ expect(data).not.toBeDefined();
84
+ expect(spy).toHaveBeenCalledTimes(0);
85
+ });
86
+ it("should remove data when version change", async () => {
87
+ await cache.options?.lazyStorage?.set(cacheKey, {
88
+ ...cacheData,
89
+ version: "old-key",
90
+ });
91
+
92
+ const deleteSpy = jest.spyOn(cache.options?.lazyStorage as CacheAsyncStorageType, "delete");
93
+ cache.events.onDataByKey(cacheKey, spy);
94
+ const data = cache.get(cacheKey);
95
+ await sleep(50);
96
+ expect(data).not.toBeDefined();
97
+ expect(spy).toHaveBeenCalledTimes(0);
98
+ expect(deleteSpy).toHaveBeenCalledTimes(1);
99
+ });
100
+ it("should delete lazy storage data", async () => {
101
+ await cache.options?.lazyStorage?.set(cacheKey, cacheData);
102
+ await cache.delete(cacheKey);
103
+ await sleep(50);
104
+ expect(await cache.options?.lazyStorage?.get(cacheKey)).not.toBeDefined();
105
+ });
106
+ it("should get keys from lazy storage and sync storage", async () => {
107
+ const otherKey = "otherKey";
108
+ await cache.options?.lazyStorage?.set(cacheKey, cacheData);
109
+ await cache.storage.set(otherKey, cacheData);
110
+ const keys = await cache.getAllKeys();
111
+ await sleep(50);
112
+ expect(keys).toStrictEqual([cacheKey, otherKey]);
113
+ });
114
+ it("should allow to get lazy cache keys", async () => {
115
+ const mockLazyKeys = ["lazy1", "lazy2", "lazy3"];
116
+ cache.lazyStorage = {
117
+ keys: jest.fn().mockResolvedValue(mockLazyKeys),
118
+ get: jest.fn(),
119
+ set: jest.fn(),
120
+ delete: jest.fn(),
121
+ };
122
+
123
+ const lazyKeys = await cache.getLazyKeys();
124
+
125
+ expect(cache.lazyStorage.keys).toHaveBeenCalled();
126
+ expect(lazyKeys).toEqual(mockLazyKeys);
127
+ });
128
+ });
129
+ });
@@ -0,0 +1,119 @@
1
+ import { getCacheData, getCacheByKey, getInvalidateByKey } from "cache";
2
+ import { ResponseErrorType, ResponseSuccessType } from "adapter";
3
+ import { ResponseDetailsType } from "managers";
4
+ import { HttpAdapterType, xhrExtra } from "http-adapter";
5
+
6
+ describe("Cache [ Utils ]", () => {
7
+ describe("when getCacheData function is used", () => {
8
+ it("should not override cache on retry or refresh error response", async () => {
9
+ const previousResponse = {
10
+ data: {},
11
+ error: null,
12
+ status: 200,
13
+ extra: xhrExtra,
14
+ } as ResponseSuccessType<Record<string, string>, HttpAdapterType>;
15
+ const errorResponse: ResponseErrorType<Record<string, string>, HttpAdapterType> & ResponseDetailsType = {
16
+ data: null,
17
+ error: {},
18
+ status: 400,
19
+ success: false,
20
+ extra: xhrExtra,
21
+ retries: 0,
22
+ requestTimestamp: +new Date(),
23
+ responseTimestamp: +new Date(),
24
+ addedTimestamp: +new Date(),
25
+ triggerTimestamp: +new Date(),
26
+ isCanceled: false,
27
+ isOffline: false,
28
+ };
29
+
30
+ expect(getCacheData(previousResponse, errorResponse)).toStrictEqual({
31
+ data: previousResponse.data,
32
+ error: errorResponse.error,
33
+ status: errorResponse.status,
34
+ success: errorResponse.success,
35
+ extra: errorResponse.extra,
36
+ retries: 0,
37
+ requestTimestamp: expect.toBeNumber(),
38
+ responseTimestamp: expect.toBeNumber(),
39
+ addedTimestamp: expect.toBeNumber(),
40
+ triggerTimestamp: expect.toBeNumber(),
41
+ isCanceled: false,
42
+ isOffline: false,
43
+ } satisfies ReturnType<typeof getCacheData>);
44
+ });
45
+
46
+ it("should use successful response over previous data", async () => {
47
+ const previousResponse = {
48
+ data: { test: "1" },
49
+ error: null,
50
+ status: 200,
51
+ success: true,
52
+ extra: xhrExtra,
53
+ retries: 0,
54
+ requestTimestamp: +new Date(),
55
+ responseTimestamp: +new Date(),
56
+ addedTimestamp: +new Date(),
57
+ triggerTimestamp: +new Date(),
58
+ isCanceled: false,
59
+ isOffline: false,
60
+ } as ResponseSuccessType<Record<string, string>, HttpAdapterType> & ResponseDetailsType;
61
+ const newResponse = {
62
+ data: { test: "2" },
63
+ error: null,
64
+ status: 200,
65
+ success: true,
66
+ extra: xhrExtra,
67
+ retries: 0,
68
+ requestTimestamp: +new Date(),
69
+ responseTimestamp: +new Date(),
70
+ addedTimestamp: +new Date(),
71
+ triggerTimestamp: +new Date(),
72
+ isCanceled: false,
73
+ isOffline: false,
74
+ } as ResponseSuccessType<Record<string, string>, HttpAdapterType> & ResponseDetailsType;
75
+ expect(getCacheData(previousResponse, newResponse)).toStrictEqual(newResponse);
76
+ });
77
+
78
+ it("should use any response if there is no cached data", async () => {
79
+ const newResponse = {
80
+ data: {},
81
+ error: null,
82
+ status: 200,
83
+ success: true,
84
+ extra: xhrExtra,
85
+ retries: 0,
86
+ requestTimestamp: expect.toBeNumber(),
87
+ responseTimestamp: expect.toBeNumber(),
88
+ addedTimestamp: expect.toBeNumber(),
89
+ triggerTimestamp: expect.toBeNumber(),
90
+ isCanceled: false,
91
+ isOffline: false,
92
+ } as ResponseSuccessType<Record<string, string>, HttpAdapterType> & ResponseDetailsType;
93
+ const errorResponse = {
94
+ data: null,
95
+ error: {},
96
+ status: 400,
97
+ success: false,
98
+ extra: xhrExtra,
99
+ retries: 0,
100
+ requestTimestamp: expect.toBeNumber(),
101
+ responseTimestamp: expect.toBeNumber(),
102
+ addedTimestamp: expect.toBeNumber(),
103
+ triggerTimestamp: expect.toBeNumber(),
104
+ isCanceled: false,
105
+ isOffline: false,
106
+ } as ResponseErrorType<Record<string, string>, HttpAdapterType> & ResponseDetailsType;
107
+ expect(getCacheData(undefined, newResponse)).toStrictEqual(newResponse);
108
+ expect(getCacheData(undefined, errorResponse)).toStrictEqual(errorResponse);
109
+ });
110
+ });
111
+ describe("when key getters are triggered", () => {
112
+ it("should get proper key from getInvalidateByKey", async () => {
113
+ expect(getInvalidateByKey("1")).toBe("1_invalidate");
114
+ });
115
+ it("should get proper key from getCacheByKey", async () => {
116
+ expect(getCacheByKey("1")).toBe("1_cache");
117
+ });
118
+ });
119
+ });
@@ -0,0 +1,125 @@
1
+ import { createHttpMockingServer } from "@hyper-fetch/testing";
2
+
3
+ import { Client } from "client";
4
+
5
+ const { resetMocks, startServer, stopServer, mockRequest } = createHttpMockingServer();
6
+
7
+ describe("Client [ Auth ]", () => {
8
+ const requestFixture = { data: "" };
9
+
10
+ const refreshFixture = { token: "new-token" };
11
+ const refreshEndpoint = "/refresh-token";
12
+
13
+ let client = new Client({ url: "shared-base-url" });
14
+ let request = client.createRequest<{ response: any }>()({ endpoint: "/shared-endpoint" }).setAuth(false);
15
+ let authRequest = client.createRequest<{ response: any }>()({ endpoint: "/auth" }).setAuth(true);
16
+ let refreshRequest = client.createRequest<{ response: any }>()({ endpoint: refreshEndpoint });
17
+
18
+ beforeEach(() => {
19
+ mockRequest(refreshRequest, { data: refreshFixture });
20
+ });
21
+
22
+ beforeAll(() => {
23
+ startServer();
24
+ });
25
+
26
+ afterEach(() => {
27
+ client = new Client({ url: "shared-base-url" });
28
+ request = client.createRequest<{ response: any }>()({ endpoint: "/shared-endpoint" }).setAuth(false);
29
+ authRequest = client.createRequest<{ response: any }>()({ endpoint: "/auth" }).setAuth(true);
30
+ refreshRequest = client.createRequest<{ response: any }>()({ endpoint: refreshEndpoint });
31
+ resetMocks();
32
+ jest.resetAllMocks();
33
+ });
34
+
35
+ afterAll(() => {
36
+ stopServer();
37
+ });
38
+
39
+ describe("When authenticated request get send", () => {
40
+ it("should trigger auth middleware callback", async () => {
41
+ mockRequest(authRequest, { data: requestFixture });
42
+
43
+ const trigger = jest.fn();
44
+
45
+ client.onAuth((cmd) => {
46
+ trigger();
47
+ return cmd;
48
+ });
49
+
50
+ await authRequest.send({});
51
+
52
+ expect(trigger).toHaveBeenCalledTimes(1);
53
+ });
54
+ });
55
+
56
+ describe("When non-authenticated request get send", () => {
57
+ it("should trigger auth middleware callback", async () => {
58
+ mockRequest(request, { data: requestFixture });
59
+
60
+ const trigger = jest.fn();
61
+
62
+ client.onAuth((cmd) => {
63
+ trigger();
64
+ return cmd;
65
+ });
66
+
67
+ await request.send({});
68
+
69
+ expect(trigger).toHaveBeenCalledTimes(0);
70
+ });
71
+ });
72
+
73
+ describe("When token is out of date", () => {
74
+ const interceptor = jest.fn();
75
+
76
+ const handleErrorIntercept = (callback?: () => void) => {
77
+ client.onError(async (res, req) => {
78
+ interceptor();
79
+ const { status } = res;
80
+
81
+ if (!req.used && status === 401) {
82
+ const { data } = await refreshRequest.send({});
83
+ if (data) {
84
+ callback?.();
85
+ return req.setUsed(true).send({});
86
+ }
87
+ }
88
+ return res;
89
+ });
90
+ };
91
+
92
+ it("should intercept error response and get the data with new token", async () => {
93
+ mockRequest(request, { status: 401 });
94
+
95
+ handleErrorIntercept(() => mockRequest(request, { data: requestFixture }));
96
+
97
+ const response = await request.send({});
98
+ expect(response.data).toEqual(requestFixture);
99
+ expect(interceptor).toHaveBeenCalledTimes(1);
100
+ });
101
+ it("should intercept error response and return error after another failure", async () => {
102
+ const errorResponse = mockRequest(request, { status: 401 });
103
+
104
+ handleErrorIntercept();
105
+ const { data, error, status } = await request.send({});
106
+
107
+ expect(status).toBe(401);
108
+ expect(data).toBe(null);
109
+ expect(error).toEqual(errorResponse);
110
+ expect(interceptor).toHaveBeenCalledTimes(2);
111
+ });
112
+
113
+ it("should try to repeat request only once", async () => {
114
+ mockRequest(request, { status: 401 });
115
+
116
+ const retry = jest.fn();
117
+
118
+ handleErrorIntercept(retry);
119
+
120
+ await request.send({});
121
+
122
+ expect(retry).toHaveBeenCalledTimes(1);
123
+ });
124
+ });
125
+ });
@@ -0,0 +1,149 @@
1
+ import { createHttpMockingServer } from "@hyper-fetch/testing";
2
+
3
+ import { Cache } from "cache";
4
+ import { Dispatcher } from "dispatcher";
5
+ import { AppManager } from "managers";
6
+ import { Client } from "client";
7
+ import { Adapter } from "adapter";
8
+
9
+ const { resetMocks, startServer, stopServer } = createHttpMockingServer();
10
+
11
+ describe("Client [ Base ]", () => {
12
+ beforeAll(() => {
13
+ startServer();
14
+ });
15
+
16
+ beforeEach(() => {
17
+ resetMocks();
18
+ });
19
+
20
+ afterAll(() => {
21
+ stopServer();
22
+ });
23
+
24
+ describe("When client properties are passed", () => {
25
+ it("should assign url", async () => {
26
+ const url = "test-123";
27
+ const client = new Client({ url });
28
+
29
+ expect(client.url).toBe(url);
30
+ });
31
+ it("should assign new adapter", async () => {
32
+ const adapter = new Adapter({
33
+ name: "test",
34
+ defaultMethod: "GET",
35
+ defaultExtra: {},
36
+ systemErrorStatus: 0,
37
+ systemErrorExtra: {},
38
+ });
39
+ const client = new Client({ url: "shared-base-url" }).setAdapter(adapter);
40
+
41
+ expect(client.adapter).toBe(adapter);
42
+ });
43
+ it("should assign new appManager", async () => {
44
+ const appManager = new AppManager();
45
+ const client = new Client({ url: "shared-base-url", appManager: () => appManager });
46
+
47
+ expect(client.appManager).toBe(appManager);
48
+ });
49
+ it("should assign new cache", async () => {
50
+ const cache = new Cache();
51
+ const client = new Client({ url: "shared-base-url", cache: () => cache });
52
+
53
+ expect(client.cache).toBe(cache);
54
+ });
55
+ it("should assign new fetchDispatcher", async () => {
56
+ const fetchDispatcher = new Dispatcher();
57
+ const client = new Client({ url: "shared-base-url", fetchDispatcher: () => fetchDispatcher });
58
+
59
+ expect(client.fetchDispatcher).toBe(fetchDispatcher);
60
+ });
61
+ it("should assign new submitDispatcher", async () => {
62
+ const submitDispatcher = new Dispatcher();
63
+ const client = new Client({ url: "shared-base-url", submitDispatcher: () => submitDispatcher });
64
+
65
+ expect(client.submitDispatcher).toBe(submitDispatcher);
66
+ });
67
+ });
68
+ describe("When client is getting cleared", () => {
69
+ it("should assign new appManager", async () => {
70
+ const spy = jest.fn();
71
+ const appManager = new AppManager();
72
+ const client = new Client({
73
+ url: "shared-base-url",
74
+ appManager: () => {
75
+ spy();
76
+ return appManager;
77
+ },
78
+ });
79
+ expect(spy).toHaveBeenCalledTimes(1);
80
+ client.clear();
81
+ expect(spy).toHaveBeenCalledTimes(2);
82
+ });
83
+ it("should assign new cache", async () => {
84
+ const spy = jest.fn();
85
+ const cache = new Cache();
86
+ const client = new Client({
87
+ url: "shared-base-url",
88
+ cache: () => {
89
+ spy();
90
+ return cache;
91
+ },
92
+ });
93
+
94
+ expect(spy).toHaveBeenCalledTimes(1);
95
+ client.clear();
96
+ expect(spy).toHaveBeenCalledTimes(2);
97
+ });
98
+ it("should assign new fetchDispatcher", async () => {
99
+ const spy = jest.fn();
100
+ const fetchDispatcher = new Dispatcher();
101
+ const client = new Client({
102
+ url: "shared-base-url",
103
+ fetchDispatcher: () => {
104
+ spy();
105
+ return fetchDispatcher;
106
+ },
107
+ });
108
+
109
+ expect(spy).toHaveBeenCalledTimes(1);
110
+ client.clear();
111
+ expect(spy).toHaveBeenCalledTimes(2);
112
+ });
113
+ it("should assign new submitDispatcher", async () => {
114
+ const spy = jest.fn();
115
+ const submitDispatcher = new Dispatcher();
116
+ const client = new Client({
117
+ url: "shared-base-url",
118
+ submitDispatcher: () => {
119
+ spy();
120
+ return submitDispatcher;
121
+ },
122
+ });
123
+
124
+ expect(spy).toHaveBeenCalledTimes(1);
125
+ client.clear();
126
+ expect(spy).toHaveBeenCalledTimes(2);
127
+ });
128
+ it("should assign new defaultExtra", async () => {
129
+ const defaultExtra = { headers: { test: "1" } };
130
+ const client = new Client({
131
+ url: "shared-base-url",
132
+ });
133
+
134
+ client.adapter.setDefaultExtra(defaultExtra);
135
+
136
+ expect(client.adapter.defaultExtra).toStrictEqual(defaultExtra);
137
+ });
138
+ it("should assign new defaultMethod", async () => {
139
+ const defaultMethod = "POST";
140
+ const client = new Client({
141
+ url: "shared-base-url",
142
+ });
143
+
144
+ client.adapter.setDefaultMethod(defaultMethod);
145
+
146
+ expect(client.adapter.defaultMethod).toStrictEqual(defaultMethod);
147
+ });
148
+ });
149
+ });