| 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 | describe('ReactDOMNestedEvents', () => { |
| 13 | let React; |
| 14 | let ReactDOMClient; |
| 15 | let Scheduler; |
| 16 | let act; |
| 17 | let useState; |
| 18 | let assertLog; |
| 19 | |
| 20 | beforeEach(() => { |
| 21 | jest.resetModules(); |
| 22 | React = require('react'); |
| 23 | ReactDOMClient = require('react-dom/client'); |
| 24 | Scheduler = require('scheduler'); |
| 25 | act = require('internal-test-utils').act; |
| 26 | useState = React.useState; |
| 27 | |
| 28 | const InternalTestUtils = require('internal-test-utils'); |
| 29 | assertLog = InternalTestUtils.assertLog; |
| 30 | }); |
| 31 | |
| 32 | it('nested event dispatches should not cause updates to flush', async () => { |
| 33 | const buttonRef = React.createRef(null); |
| 34 | function App() { |
| 35 | const [isClicked, setIsClicked] = useState(false); |
| 36 | const [isFocused, setIsFocused] = useState(false); |
| 37 | const onClick = () => { |
| 38 | setIsClicked(true); |
| 39 | const el = buttonRef.current; |
| 40 | el.focus(); |
| 41 | // The update triggered by the focus event should not have flushed yet. |
| 42 | // Nor the click update. They would have if we had wrapped the focus |
| 43 | // call in `flushSync`, though. |
| 44 | Scheduler.log('Value right after focus call: ' + el.innerHTML); |
| 45 | }; |
| 46 | const onFocus = () => { |
| 47 | setIsFocused(true); |
| 48 | }; |
| 49 | return ( |
| 50 | <> |
| 51 | <button ref={buttonRef} onFocus={onFocus} onClick={onClick}> |
| 52 | {`Clicked: ${isClicked}, Focused: ${isFocused}`} |
| 53 | </button> |
| 54 | </> |
| 55 | ); |
| 56 | } |
| 57 | |
| 58 | const container = document.createElement('div'); |
| 59 | document.body.appendChild(container); |
| 60 | const root = ReactDOMClient.createRoot(container); |
| 61 | |
| 62 | await act(() => { |
| 63 | root.render(<App />); |
| 64 | }); |
| 65 | expect(buttonRef.current.innerHTML).toEqual( |
| 66 | 'Clicked: false, Focused: false', |
| 67 | ); |
| 68 | |
| 69 | await act(() => { |
| 70 | buttonRef.current.click(); |
| 71 | }); |
| 72 | assertLog(['Value right after focus call: Clicked: false, Focused: false']); |
| 73 | expect(buttonRef.current.innerHTML).toEqual('Clicked: true, Focused: true'); |
| 74 | }); |
| 75 | }); |