forked from facebook/react
-
Notifications
You must be signed in to change notification settings - Fork 9
/
ReactCacheOld-test.internal.js
384 lines (341 loc) · 10.7 KB
/
ReactCacheOld-test.internal.js
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let ReactCache;
let createResource;
let React;
let ReactFeatureFlags;
let ReactTestRenderer;
let Scheduler;
let Suspense;
let TextResource;
let textResourceShouldFail;
describe('ReactCache', () => {
beforeEach(() => {
jest.resetModules();
ReactFeatureFlags = require('shared/ReactFeatureFlags');
ReactFeatureFlags.replayFailedUnitOfWorkWithInvokeGuardedCallback = false;
React = require('react');
Suspense = React.Suspense;
ReactCache = require('react-cache');
createResource = ReactCache.unstable_createResource;
ReactTestRenderer = require('react-test-renderer');
Scheduler = require('scheduler');
TextResource = createResource(
([text, ms = 0]) => {
let listeners = null;
let status = 'pending';
let value = null;
return {
then(resolve, reject) {
switch (status) {
case 'pending': {
if (listeners === null) {
listeners = [{resolve, reject}];
setTimeout(() => {
if (textResourceShouldFail) {
Scheduler.unstable_yieldValue(
`Promise rejected [${text}]`,
);
status = 'rejected';
value = new Error('Failed to load: ' + text);
listeners.forEach(listener => listener.reject(value));
} else {
Scheduler.unstable_yieldValue(
`Promise resolved [${text}]`,
);
status = 'resolved';
value = text;
listeners.forEach(listener => listener.resolve(value));
}
}, ms);
} else {
listeners.push({resolve, reject});
}
break;
}
case 'resolved': {
resolve(value);
break;
}
case 'rejected': {
reject(value);
break;
}
}
},
};
},
([text, ms]) => text,
);
textResourceShouldFail = false;
});
function Text(props) {
Scheduler.unstable_yieldValue(props.text);
return props.text;
}
function AsyncText(props) {
const text = props.text;
try {
TextResource.read([props.text, props.ms]);
Scheduler.unstable_yieldValue(text);
return text;
} catch (promise) {
if (typeof promise.then === 'function') {
Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
} else {
Scheduler.unstable_yieldValue(`Error! [${text}]`);
}
throw promise;
}
}
it('throws a promise if the requested value is not in the cache', () => {
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText ms={100} text="Hi" />
</Suspense>
);
}
ReactTestRenderer.create(<App />, {
unstable_isConcurrent: true,
});
expect(Scheduler).toFlushAndYield(['Suspend! [Hi]', 'Loading...']);
jest.advanceTimersByTime(100);
expect(Scheduler).toHaveYielded(['Promise resolved [Hi]']);
expect(Scheduler).toFlushAndYield(['Hi']);
});
it('throws an error on the subsequent read if the promise is rejected', async () => {
function App() {
return (
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText ms={100} text="Hi" />
</Suspense>
);
}
const root = ReactTestRenderer.create(<App />, {
unstable_isConcurrent: true,
});
expect(Scheduler).toFlushAndYield(['Suspend! [Hi]', 'Loading...']);
textResourceShouldFail = true;
jest.advanceTimersByTime(100);
expect(Scheduler).toHaveYielded(['Promise rejected [Hi]']);
expect(Scheduler).toFlushAndThrow('Failed to load: Hi');
expect(Scheduler).toHaveYielded(['Error! [Hi]', 'Error! [Hi]']);
// Should throw again on a subsequent read
root.update(<App />);
expect(Scheduler).toFlushAndThrow('Failed to load: Hi');
expect(Scheduler).toHaveYielded(['Error! [Hi]', 'Error! [Hi]']);
});
it('warns if non-primitive key is passed to a resource without a hash function', () => {
const BadTextResource = createResource(([text, ms = 0]) => {
return new Promise((resolve, reject) =>
setTimeout(() => {
resolve(text);
}, ms),
);
});
function App() {
Scheduler.unstable_yieldValue('App');
return BadTextResource.read(['Hi', 100]);
}
ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<App />
</Suspense>,
{
unstable_isConcurrent: true,
},
);
if (__DEV__) {
expect(() => {
expect(Scheduler).toFlushAndYield(['App', 'Loading...']);
}).toErrorDev([
'Invalid key type. Expected a string, number, symbol, or ' +
'boolean, but instead received: Hi,100\n\n' +
'To use non-primitive values as keys, you must pass a hash ' +
'function as the second argument to createResource().',
]);
} else {
expect(Scheduler).toFlushAndYield(['App', 'Loading...']);
}
});
it('evicts least recently used values', async () => {
ReactCache.unstable_setGlobalCacheLimit(3);
// Render 1, 2, and 3
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText ms={100} text={1} />
<AsyncText ms={100} text={2} />
<AsyncText ms={100} text={3} />
</Suspense>,
{
unstable_isConcurrent: true,
},
);
expect(Scheduler).toFlushAndYield([
'Suspend! [1]',
'Suspend! [2]',
'Suspend! [3]',
'Loading...',
]);
jest.advanceTimersByTime(100);
expect(Scheduler).toHaveYielded([
'Promise resolved [1]',
'Promise resolved [2]',
'Promise resolved [3]',
]);
expect(Scheduler).toFlushAndYield([1, 2, 3]);
expect(root).toMatchRenderedOutput('123');
// Render 1, 4, 5
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText ms={100} text={1} />
<AsyncText ms={100} text={4} />
<AsyncText ms={100} text={5} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield([
1,
'Suspend! [4]',
'Suspend! [5]',
'Loading...',
]);
jest.advanceTimersByTime(100);
expect(Scheduler).toHaveYielded([
'Promise resolved [4]',
'Promise resolved [5]',
]);
expect(Scheduler).toFlushAndYield([1, 4, 5]);
expect(root).toMatchRenderedOutput('145');
// We've now rendered values 1, 2, 3, 4, 5, over our limit of 3. The least
// recently used values are 2 and 3. They should have been evicted.
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<AsyncText ms={100} text={1} />
<AsyncText ms={100} text={2} />
<AsyncText ms={100} text={3} />
</Suspense>,
);
expect(Scheduler).toFlushAndYield([
// 1 is still cached
1,
// 2 and 3 suspend because they were evicted from the cache
'Suspend! [2]',
'Suspend! [3]',
'Loading...',
]);
jest.advanceTimersByTime(100);
expect(Scheduler).toHaveYielded([
'Promise resolved [2]',
'Promise resolved [3]',
]);
expect(Scheduler).toFlushAndYield([1, 2, 3]);
expect(root).toMatchRenderedOutput('123');
});
it('preloads during the render phase', async () => {
function App() {
TextResource.preload(['B', 1000]);
TextResource.read(['A', 1000]);
TextResource.read(['B', 1000]);
return <Text text="Result" />;
}
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<App />
</Suspense>,
{
unstable_isConcurrent: true,
},
);
expect(Scheduler).toFlushAndYield(['Loading...']);
jest.advanceTimersByTime(1000);
expect(Scheduler).toHaveYielded([
'Promise resolved [B]',
'Promise resolved [A]',
]);
expect(Scheduler).toFlushAndYield(['Result']);
expect(root).toMatchRenderedOutput('Result');
});
it('if a thenable resolves multiple times, does not update the first cached value', () => {
let resolveThenable;
const BadTextResource = createResource(
([text, ms = 0]) => {
let listeners = null;
const value = null;
return {
then(resolve, reject) {
if (value !== null) {
resolve(value);
} else {
if (listeners === null) {
listeners = [resolve];
resolveThenable = v => {
listeners.forEach(listener => listener(v));
};
} else {
listeners.push(resolve);
}
}
},
};
},
([text, ms]) => text,
);
function BadAsyncText(props) {
const text = props.text;
try {
const actualText = BadTextResource.read([props.text, props.ms]);
Scheduler.unstable_yieldValue(actualText);
return actualText;
} catch (promise) {
if (typeof promise.then === 'function') {
Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
} else {
Scheduler.unstable_yieldValue(`Error! [${text}]`);
}
throw promise;
}
}
const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<BadAsyncText text="Hi" />
</Suspense>,
{
unstable_isConcurrent: true,
},
);
expect(Scheduler).toFlushAndYield(['Suspend! [Hi]', 'Loading...']);
resolveThenable('Hi');
// This thenable improperly resolves twice. We should not update the
// cached value.
resolveThenable('Hi muahahaha I am different');
root.update(
<Suspense fallback={<Text text="Loading..." />}>
<BadAsyncText text="Hi" />
</Suspense>,
{
unstable_isConcurrent: true,
},
);
expect(Scheduler).toHaveYielded([]);
expect(Scheduler).toFlushAndYield(['Hi']);
expect(root).toMatchRenderedOutput('Hi');
});
it('throws if read is called outside render', () => {
expect(() => TextResource.read(['A', 1000])).toThrow(
"read and preload may only be called from within a component's render",
);
});
it('throws if preload is called outside render', () => {
expect(() => TextResource.preload(['A', 1000])).toThrow(
"read and preload may only be called from within a component's render",
);
});
});