-
-
Notifications
You must be signed in to change notification settings - Fork 92
/
fetch.tsx
296 lines (274 loc) · 8.31 KB
/
fetch.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import { ResolveType } from '@data-client/core';
import { CacheProvider } from '@data-client/react';
import { CacheProvider as ExternalCacheProvider } from '@data-client/redux';
import { CoolerArticle, FutureArticleResource } from '__tests__/new';
import nock from 'nock';
import { useCache, useSuspense } from '../..';
// relative imports to avoid circular dependency in tsconfig references
import {
makeRenderDataClient,
FixtureEndpoint,
act,
} from '../../../../../test';
import useController from '../../useController';
export const payload = {
id: 5,
title: 'hi ho',
content: 'whatever',
tags: ['a', 'best', 'react'],
};
export const createPayload = {
id: 1,
title: 'hi ho',
content: 'whatever',
tags: ['a', 'best', 'react'],
};
export const nested = [
{
id: 5,
title: 'hi ho',
content: 'whatever',
tags: ['a', 'best', 'react'],
author: {
id: 23,
username: 'bob',
},
},
{
id: 3,
title: 'the next time',
content: 'whatever',
author: {
id: 23,
username: 'charles',
email: 'bob@bob.com',
},
},
];
describe.each([
['CacheProvider', CacheProvider],
['ExternalCacheProvider', ExternalCacheProvider],
] as const)(`%s`, (_, makeProvider) => {
// TODO: add nested resource test case that has multiple partials to test merge functionality
let renderDataClient: ReturnType<typeof makeRenderDataClient>;
let mynock: nock.Scope;
beforeEach(() => {
nock(/.*/)
.persist()
.defaultReplyHeaders({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
})
.options(/.*/)
.reply(200)
.get(`/article-cooler/${payload.id}`)
.reply(200, payload)
.delete(`/article-cooler/${payload.id}`)
.reply(204, '')
.delete(`/article/${payload.id}`)
.reply(200, {})
.get(`/article-cooler/0`)
.reply(403, {})
.get(`/article-cooler/666`)
.reply(200, '')
.get(`/article-cooler`)
.reply(200, nested)
.post(`/article-cooler`)
.reply(200, createPayload);
mynock = nock(/.*/).defaultReplyHeaders({
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json',
});
});
afterEach(() => {
nock.cleanAll();
});
beforeEach(() => {
renderDataClient = makeRenderDataClient(makeProvider);
});
let errorspy: jest.SpyInstance;
beforeEach(() => {
errorspy = jest.spyOn(global.console, 'error').mockImplementation(() => {});
jest.spyOn(global.console, 'warn').mockImplementation(() => {});
});
afterEach(() => {
errorspy.mockRestore();
});
it('should fetch', async () => {
const { result } = renderDataClient(() => {
return {
data: useCache(FutureArticleResource.get, payload.id),
fetch: useController().fetch,
};
});
expect(result.current.data).toBeUndefined();
result.current.fetch(FutureArticleResource.get, payload.id);
result.current.fetch(FutureArticleResource.get, payload.id);
result.current.fetch(FutureArticleResource.get, payload.id);
const response = await result.current.fetch(
FutureArticleResource.get,
payload.id,
);
expect(result.current.data).toBeDefined();
expect(result.current.data?.content).toEqual(payload.content);
expect(response).toEqual(CoolerArticle.fromJS(payload));
expect(response.content).toBe(payload.content);
// @ts-expect-error
() => response.slkdf;
// type tests
// TODO: move these to own unit tests if/when applicable
() => {
// @ts-expect-error
result.current.fetch(FutureArticleResource.get);
// @ts-expect-error
result.current.fetch(FutureArticleResource.get, {
id: payload.id,
});
result.current.fetch(FutureArticleResource.create, payload);
// @ts-expect-error
result.current.fetch(FutureArticleResource.create, {}, payload);
result.current.fetch(FutureArticleResource.update, payload.id, payload);
// @ts-expect-error
result.current.fetch(FutureArticleResource.update, payload);
};
});
it('should fetch with resolver', async () => {
// we use this id because it is not nock'd
const id = 10000;
const fixture = {
endpoint: FutureArticleResource.get,
args: [10000],
response: payload,
};
const { result } = renderDataClient(
() => {
return {
data: useCache(FutureArticleResource.get, id),
fetch: useController().fetch,
};
},
{ resolverFixtures: [fixture] },
);
expect(result.current.data).toBeUndefined();
result.current.fetch(FutureArticleResource.get, id);
result.current.fetch(FutureArticleResource.get, id);
result.current.fetch(FutureArticleResource.get, id);
await result.current.fetch(FutureArticleResource.get, id);
});
it('should update on create', async () => {
const endpoint = FutureArticleResource.create;
const response: ResolveType<typeof endpoint> = createPayload;
const fixtures: FixtureEndpoint[] = [
{
endpoint,
args: [{ id: 1 }],
response,
},
];
// use nock, and use resolver
for (const resolverFixtures of [undefined, fixtures]) {
const { result, waitForNextUpdate } = renderDataClient(
() => {
const articles = useSuspense(FutureArticleResource.getList);
const fetch = useController().fetch;
return { articles, fetch };
},
{ resolverFixtures },
);
await waitForNextUpdate();
await act(async () => {
const article = await result.current.fetch(
FutureArticleResource.create,
{
id: 1,
},
);
article.content;
// @ts-expect-error
article.asdf;
article.pk();
});
expect(result.current.articles.map(({ id }) => id)).toEqual([5, 3, 1]);
}
});
it('should log error message when user update method throws', async () => {
const endpoint = FutureArticleResource.create.extend({
schema: CoolerArticle,
update: () => {
throw new Error('usererror');
},
});
const response: ResolveType<typeof endpoint> = createPayload;
const fixtures: FixtureEndpoint[] = [
{
endpoint,
args: [{ id: 1 }],
response,
},
];
const { result, waitForNextUpdate } = renderDataClient(
() => {
const articles = useSuspense(FutureArticleResource.getList);
const fetch = useController().fetch;
return { articles, fetch };
},
{ resolverFixtures: fixtures },
);
await waitForNextUpdate();
await act(async () => {
await result.current.fetch(endpoint, {
id: 1,
});
}),
// still keeps old list
expect(result.current.articles.map(({ id }) => id)).toEqual([5, 3]);
expect(errorspy.mock.calls[0]).toMatchSnapshot();
});
it('should not suspend once deleted and redirected at same time', async () => {
const temppayload = {
...payload,
id: 1234,
};
mynock
.get(`/article-cooler/${temppayload.id}`)
.reply(200, temppayload)
.delete(`/article-cooler/${temppayload.id}`)
.reply(204, '');
const throws: Promise<any>[] = [];
const { result, waitForNextUpdate, rerender } = renderDataClient(
({ id }) => {
try {
return [
useSuspense(FutureArticleResource.get, id) ?? null,
useController().fetch,
] as const;
} catch (e: any) {
if (typeof e.then === 'function') {
if (e !== throws[throws.length - 1]) {
throws.push(e);
}
}
throw e;
}
},
{ initialProps: { id: temppayload.id as number | null } },
);
expect(result.current).toBeUndefined();
await waitForNextUpdate();
const [data, fetch] = result.current;
expect(data).toBeInstanceOf(CoolerArticle);
expect(data?.title).toBe(temppayload.title);
expect(throws.length).toBe(1);
mynock
.persist()
.get(`/article-cooler/${temppayload.id}`)
.reply(200, { ...temppayload, title: 'othertitle' });
expect(throws.length).toBe(1);
await act(async () => {
await fetch(FutureArticleResource.delete, temppayload.id);
rerender({ id: null });
});
expect(throws.length).toBe(1);
expect(result.current[0]).toBe(null);
});
});