1. /**
    
  2.  * Copyright (c) Meta Platforms, Inc. and 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.AsyncLocalStorage = require('async_hooks').AsyncLocalStorage;
    
  17. 
    
  18. let React;
    
  19. let ReactDOM;
    
  20. let ReactDOMFizzServer;
    
  21. 
    
  22. describe('ReactDOMFizzServerEdge', () => {
    
  23.   beforeEach(() => {
    
  24.     jest.resetModules();
    
  25.     jest.useRealTimers();
    
  26.     React = require('react');
    
  27.     ReactDOM = require('react-dom');
    
  28.     ReactDOMFizzServer = require('react-dom/server.edge');
    
  29.   });
    
  30. 
    
  31.   async function readResult(stream) {
    
  32.     const reader = stream.getReader();
    
  33.     let result = '';
    
  34.     while (true) {
    
  35.       const {done, value} = await reader.read();
    
  36.       if (done) {
    
  37.         return result;
    
  38.       }
    
  39.       result += Buffer.from(value).toString('utf8');
    
  40.     }
    
  41.   }
    
  42. 
    
  43.   // https://github.com/facebook/react/issues/27540
    
  44.   it('does not try to write to the stream after it has been closed', async () => {
    
  45.     async function preloadLate() {
    
  46.       await 1;
    
  47.       await 1;
    
  48.       // need to wait a few microtasks to get the stream to close before this is called
    
  49.       ReactDOM.preconnect('foo');
    
  50.     }
    
  51. 
    
  52.     function Preload() {
    
  53.       preloadLate();
    
  54.       return null;
    
  55.     }
    
  56. 
    
  57.     function App() {
    
  58.       return (
    
  59.         <html>
    
  60.           <body>
    
  61.             <main>hello</main>
    
  62.             <Preload />
    
  63.           </body>
    
  64.         </html>
    
  65.       );
    
  66.     }
    
  67.     const stream = await ReactDOMFizzServer.renderToReadableStream(<App />);
    
  68.     const result = await readResult(stream);
    
  69.     // need to wait a macrotask to let the scheduled work from the preconnect to execute
    
  70.     await new Promise(resolve => {
    
  71.       setTimeout(resolve, 1);
    
  72.     });
    
  73. 
    
  74.     expect(result).toMatchInlineSnapshot(
    
  75.       `"<!DOCTYPE html><html><head></head><body><main>hello</main></body></html>"`,
    
  76.     );
    
  77.   });
    
  78. });