| 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 ReactDOMClient; |
| 14 | let act; |
| 15 | |
| 16 | describe('ReactEventIndependence', () => { |
| 17 | beforeEach(() => { |
| 18 | jest.resetModules(); |
| 19 | |
| 20 | React = require('react'); |
| 21 | ReactDOMClient = require('react-dom/client'); |
| 22 | act = require('internal-test-utils').act; |
| 23 | }); |
| 24 | |
| 25 | it('does not crash with other react inside', async () => { |
| 26 | let clicks = 0; |
| 27 | const container = document.createElement('div'); |
| 28 | document.body.appendChild(container); |
| 29 | const root = ReactDOMClient.createRoot(container); |
| 30 | try { |
| 31 | await act(() => { |
| 32 | root.render( |
| 33 | <div |
| 34 | onClick={() => clicks++} |
| 35 | dangerouslySetInnerHTML={{ |
| 36 | __html: '<button data-reactid=".z">click me</div>', |
| 37 | }} |
| 38 | />, |
| 39 | ); |
| 40 | }); |
| 41 | |
| 42 | container.firstElementChild.click(); |
| 43 | expect(clicks).toBe(1); |
| 44 | } finally { |
| 45 | document.body.removeChild(container); |
| 46 | } |
| 47 | }); |
| 48 | |
| 49 | it('does not crash with other react outside', async () => { |
| 50 | let clicks = 0; |
| 51 | const outer = document.createElement('div'); |
| 52 | document.body.appendChild(outer); |
| 53 | const root = ReactDOMClient.createRoot(outer); |
| 54 | try { |
| 55 | outer.setAttribute('data-reactid', '.z'); |
| 56 | await act(() => { |
| 57 | root.render(<button onClick={() => clicks++}>click me</button>); |
| 58 | }); |
| 59 | outer.firstElementChild.click(); |
| 60 | expect(clicks).toBe(1); |
| 61 | } finally { |
| 62 | document.body.removeChild(outer); |
| 63 | } |
| 64 | }); |
| 65 | |
| 66 | it('does not when event fired on unmounted tree', async () => { |
| 67 | let clicks = 0; |
| 68 | const container = document.createElement('div'); |
| 69 | document.body.appendChild(container); |
| 70 | try { |
| 71 | const root = ReactDOMClient.createRoot(container); |
| 72 | |
| 73 | await act(() => { |
| 74 | root.render(<button onClick={() => clicks++}>click me</button>); |
| 75 | }); |
| 76 | |
| 77 | const button = container.firstChild; |
| 78 | |
| 79 | // Now we unmount the component, as if caused by a non-React event handler |
| 80 | // for the same click we're about to simulate, like closing a layer: |
| 81 | root.unmount(); |
| 82 | button.click(); |
| 83 | |
| 84 | // Since the tree is unmounted, we don't dispatch the click event. |
| 85 | expect(clicks).toBe(0); |
| 86 | } finally { |
| 87 | document.body.removeChild(container); |
| 88 | } |
| 89 | }); |
| 90 | }); |