-
Notifications
You must be signed in to change notification settings - Fork 45.6k
/
ReactDOMFizzShellHydration-test.js
249 lines (219 loc) · 6.66 KB
/
ReactDOMFizzShellHydration-test.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
/**
* 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
*/
let React;
let ReactDOMClient;
let Scheduler;
let clientAct;
let ReactDOMFizzServer;
let Stream;
let writable;
let container = null;
let buffer = '';
let hasErrored = false;
let fatalError = undefined;
let textCache;
describe('ReactDOMFizzShellHydration', () => {
beforeEach(() => {
jest.resetModules();
React = require('react');
ReactDOMClient = require('react-dom/client');
Scheduler = require('scheduler');
clientAct = require('jest-react').act;
ReactDOMFizzServer = require('react-dom/server');
Stream = require('stream');
textCache = new Map();
container = document.createElement('div');
document.body.appendChild(container);
buffer = '';
hasErrored = false;
writable = new Stream.PassThrough();
writable.setEncoding('utf8');
writable.on('data', chunk => {
buffer += chunk;
});
writable.on('error', error => {
hasErrored = true;
fatalError = error;
});
});
afterEach(() => {
container?.remove();
container = null;
});
async function serverAct(callback) {
await callback();
// Await one turn around the event loop.
// This assumes that we'll flush everything we have so far.
await new Promise(resolve => {
setImmediate(resolve);
});
if (hasErrored) {
throw fatalError;
}
// JSDOM doesn't support stream HTML parser so we need to give it a proper fragment.
// We also want to execute any scripts that are embedded.
// We assume that we have now received a proper fragment of HTML.
const bufferedContent = buffer;
buffer = '';
const fakeBody = document.createElement('body');
fakeBody.innerHTML = bufferedContent;
while (fakeBody.firstChild) {
const node = fakeBody.firstChild;
if (node.nodeName === 'SCRIPT') {
const script = document.createElement('script');
script.textContent = node.textContent;
fakeBody.removeChild(node);
container.appendChild(script);
} else {
container.appendChild(node);
}
}
}
function resolveText(text) {
const record = textCache.get(text);
if (record === undefined) {
const newRecord = {
status: 'resolved',
value: text,
};
textCache.set(text, newRecord);
} else if (record.status === 'pending') {
const thenable = record.value;
record.status = 'resolved';
record.value = text;
thenable.pings.forEach(t => t());
}
}
function readText(text) {
const record = textCache.get(text);
if (record !== undefined) {
switch (record.status) {
case 'pending':
throw record.value;
case 'rejected':
throw record.value;
case 'resolved':
return record.value;
}
} else {
Scheduler.unstable_yieldValue(`Suspend! [${text}]`);
const thenable = {
pings: [],
then(resolve) {
if (newRecord.status === 'pending') {
thenable.pings.push(resolve);
} else {
Promise.resolve().then(() => resolve(newRecord.value));
}
},
};
const newRecord = {
status: 'pending',
value: thenable,
};
textCache.set(text, newRecord);
throw thenable;
}
}
function Text({text}) {
Scheduler.unstable_yieldValue(text);
return text;
}
function AsyncText({text}) {
readText(text);
Scheduler.unstable_yieldValue(text);
return text;
}
function resetTextCache() {
textCache = new Map();
}
test('suspending in the shell during hydration', async () => {
const div = React.createRef(null);
function App() {
return (
<div ref={div}>
<AsyncText text="Shell" />
</div>
);
}
// Server render
await resolveText('Shell');
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
expect(Scheduler).toHaveYielded(['Shell']);
const dehydratedDiv = container.getElementsByTagName('div')[0];
// Clear the cache and start rendering on the client
resetTextCache();
// Hydration suspends because the data for the shell hasn't loaded yet
await clientAct(async () => {
ReactDOMClient.hydrateRoot(container, <App />);
});
expect(Scheduler).toHaveYielded(['Suspend! [Shell]']);
expect(div.current).toBe(null);
expect(container.textContent).toBe('Shell');
// The shell loads and hydration finishes
await clientAct(async () => {
await resolveText('Shell');
});
expect(Scheduler).toHaveYielded(['Shell']);
expect(div.current).toBe(dehydratedDiv);
expect(container.textContent).toBe('Shell');
});
test('suspending in the shell during a normal client render', async () => {
// Same as previous test but during a normal client render, no hydration
function App() {
return <AsyncText text="Shell" />;
}
const root = ReactDOMClient.createRoot(container);
await clientAct(async () => {
root.render(<App />);
});
expect(Scheduler).toHaveYielded(['Suspend! [Shell]']);
await clientAct(async () => {
await resolveText('Shell');
});
expect(Scheduler).toHaveYielded(['Shell']);
expect(container.textContent).toBe('Shell');
});
test('updating the root before the shell hydrates forces a client render', async () => {
function App() {
return <AsyncText text="Shell" />;
}
// Server render
await resolveText('Shell');
await serverAct(async () => {
const {pipe} = ReactDOMFizzServer.renderToPipeableStream(<App />);
pipe(writable);
});
expect(Scheduler).toHaveYielded(['Shell']);
// Clear the cache and start rendering on the client
resetTextCache();
// Hydration suspends because the data for the shell hasn't loaded yet
const root = await clientAct(async () => {
return ReactDOMClient.hydrateRoot(container, <App />, {
onRecoverableError(error) {
Scheduler.unstable_yieldValue(error.message);
},
});
});
expect(Scheduler).toHaveYielded(['Suspend! [Shell]']);
expect(container.textContent).toBe('Shell');
await clientAct(async () => {
root.render(<Text text="New screen" />);
});
expect(Scheduler).toHaveYielded([
'This root received an early update, before anything was able ' +
'hydrate. Switched the entire root to client rendering.',
'New screen',
]);
expect(container.textContent).toBe('New screen');
});
});