/** * Copyright (c) Meta Platforms, Inc. and 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'; const ReactDOMServerIntegrationUtils = require('./utils/ReactDOMServerIntegrationTestUtils'); let React; let ReactDOMClient; let ReactDOMServer; function initModules() { // Reset warning cache. jest.resetModules(); React = require('react'); ReactDOMClient = require('react-dom/client'); ReactDOMServer = require('react-dom/server'); // Make them available to the helpers. return { ReactDOMClient, ReactDOMServer, }; } const { resetModules, asyncReactDOMRender, clientRenderOnServerString, expectMarkupMatch, } = ReactDOMServerIntegrationUtils(initModules); describe('ReactDOMServerIntegration', () => { beforeEach(() => { resetModules(); }); describe('refs', function () { it('should not run ref code on server', async () => { let refCount = 0; class RefsComponent extends React.Component { render() { return
refCount++} />; } } await expectMarkupMatch(,
); expect(refCount).toBe(0); }); it('should run ref code on client', async () => { let refCount = 0; class RefsComponent extends React.Component { render() { return
refCount++} />; } } await expectMarkupMatch(
, ); expect(refCount).toBe(1); }); it('should send the correct element to ref functions on client', async () => { let refElement = null; class RefsComponent extends React.Component { render() { return
(refElement = e)} />; } } const e = await clientRenderOnServerString(); expect(refElement).not.toBe(null); expect(refElement).toBe(e); }); // @gate !disableStringRefs it('should have string refs on client when rendered over server markup', async () => { class RefsComponent extends React.Component { render() { return
; } } const markup = ReactDOMServer.renderToString(); const root = document.createElement('div'); root.innerHTML = markup; let component = null; resetModules(); await expect(async () => { await asyncReactDOMRender( (component = e)} />, root, true, ); }).toErrorDev([ 'Component "RefsComponent" contains the string ref "myDiv". ' + 'Support for string refs will be removed in a future major release. ' + 'We recommend using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: https://react.dev/link/strict-mode-string-ref\n' + ' in div (at **)\n' + ' in RefsComponent (at **)', ]); expect(component.refs.myDiv).toBe(root.firstChild); }); }); it('should forward refs', async () => { const divRef = React.createRef(); class InnerComponent extends React.Component { render() { return
{this.props.value}
; } } const OuterComponent = React.forwardRef((props, ref) => ( )); await clientRenderOnServerString( , ); expect(divRef.current).not.toBe(null); expect(divRef.current.textContent).toBe('hello'); }); });