Skip to content

Commit ee24df3

Browse files
committed
Add test for the actual AsyncLocalStorage behavior
1 parent 3f4fd4f commit ee24df3

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/**
2+
* Copyright (c) Facebook, Inc. and its affiliates.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*
7+
* @emails react-core
8+
*/
9+
10+
'use strict';
11+
12+
// Polyfills for test environment
13+
global.ReadableStream =
14+
require('web-streams-polyfill/ponyfill/es6').ReadableStream;
15+
global.TextEncoder = require('util').TextEncoder;
16+
global.TextDecoder = require('util').TextDecoder;
17+
global.Headers = require('node-fetch').Headers;
18+
global.Request = require('node-fetch').Request;
19+
global.Response = require('node-fetch').Response;
20+
// Patch for Edge environments for global scope
21+
global.AsyncLocalStorage = require('async_hooks').AsyncLocalStorage;
22+
23+
let fetchCount = 0;
24+
async function fetchMock(resource, options) {
25+
fetchCount++;
26+
const request = new Request(resource, options);
27+
return new Response(
28+
request.method +
29+
' ' +
30+
request.url +
31+
' ' +
32+
JSON.stringify(Array.from(request.headers.entries())),
33+
);
34+
}
35+
36+
let React;
37+
let ReactServerDOMServer;
38+
let ReactServerDOMClient;
39+
let use;
40+
41+
describe('ReactFetch', () => {
42+
beforeEach(() => {
43+
jest.resetModules();
44+
fetchCount = 0;
45+
global.fetch = fetchMock;
46+
47+
if (gate(flags => !flags.www)) {
48+
jest.mock('react', () => require('react/react.shared-subset'));
49+
}
50+
51+
React = require('react');
52+
ReactServerDOMServer = require('react-server-dom-webpack/server.edge');
53+
ReactServerDOMClient = require('react-server-dom-webpack/client');
54+
use = React.use;
55+
});
56+
57+
async function render(Component) {
58+
const stream = ReactServerDOMServer.renderToReadableStream(<Component />);
59+
return ReactServerDOMClient.createFromReadableStream(stream);
60+
}
61+
62+
// @gate enableFetchInstrumentation && enableCache
63+
it('can dedupe fetches separately in interleaved renders', async () => {
64+
async function getData() {
65+
const r1 = await fetch('hi');
66+
const t1 = await r1.text();
67+
const r2 = await fetch('hi');
68+
const t2 = await r2.text();
69+
return t1 + ' ' + t2;
70+
}
71+
function Component() {
72+
return use(getData());
73+
}
74+
const render1 = render(Component);
75+
const render2 = render(Component);
76+
expect(await render1).toMatchInlineSnapshot(`"GET hi [] GET hi []"`);
77+
expect(await render2).toMatchInlineSnapshot(`"GET hi [] GET hi []"`);
78+
expect(fetchCount).toBe(2);
79+
});
80+
});

0 commit comments

Comments
 (0)