|
| 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 | +let React; |
| 13 | +let ReactNoop; |
| 14 | +let act; |
| 15 | + |
| 16 | +describe('ReactFiberRefs', () => { |
| 17 | + beforeEach(() => { |
| 18 | + jest.resetModules(); |
| 19 | + React = require('react'); |
| 20 | + ReactNoop = require('react-noop-renderer'); |
| 21 | + act = require('jest-react').act; |
| 22 | + }); |
| 23 | + |
| 24 | + test('strings refs can be codemodded to callback refs', async () => { |
| 25 | + let app; |
| 26 | + class App extends React.Component { |
| 27 | + render() { |
| 28 | + app = this; |
| 29 | + return ( |
| 30 | + <div |
| 31 | + prop="Hello!" |
| 32 | + ref={el => { |
| 33 | + // `refs` used to be a shared frozen object unless/until a string |
| 34 | + // ref attached by the reconciler, but it's not anymore so that we |
| 35 | + // can codemod string refs to userspace callback refs. |
| 36 | + this.refs.div = el; |
| 37 | + }} |
| 38 | + /> |
| 39 | + ); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + const root = ReactNoop.createRoot(); |
| 44 | + await act(async () => root.render(<App />)); |
| 45 | + expect(app.refs.div.prop).toBe('Hello!'); |
| 46 | + }); |
| 47 | + |
| 48 | + test('class refs are initialized to a frozen shared object', async () => { |
| 49 | + const refsCollection = new Set(); |
| 50 | + class Component extends React.Component { |
| 51 | + constructor(props) { |
| 52 | + super(props); |
| 53 | + refsCollection.add(this.refs); |
| 54 | + } |
| 55 | + render() { |
| 56 | + return <div />; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + const root = ReactNoop.createRoot(); |
| 61 | + await act(() => |
| 62 | + root.render( |
| 63 | + <> |
| 64 | + <Component /> |
| 65 | + <Component /> |
| 66 | + </>, |
| 67 | + ), |
| 68 | + ); |
| 69 | + |
| 70 | + expect(refsCollection.size).toBe(1); |
| 71 | + const refsInstance = Array.from(refsCollection)[0]; |
| 72 | + expect(Object.isFrozen(refsInstance)).toBe(__DEV__); |
| 73 | + }); |
| 74 | +}); |
0 commit comments