| 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 ReactTestRenderer; |
| 14 | let act; |
| 15 | let assertConsoleWarnDev; |
| 16 | let useState; |
| 17 | let useTransition; |
| 18 | |
| 19 | const SUSPICIOUS_NUMBER_OF_FIBERS_UPDATED = 10; |
| 20 | |
| 21 | describe('ReactStartTransition', () => { |
| 22 | beforeEach(() => { |
| 23 | jest.resetModules(); |
| 24 | React = require('react'); |
| 25 | ReactTestRenderer = require('react-test-renderer'); |
| 26 | ({act, assertConsoleWarnDev} = require('internal-test-utils')); |
| 27 | useState = React.useState; |
| 28 | useTransition = React.useTransition; |
| 29 | }); |
| 30 | |
| 31 | it('Warns if a suspicious number of fibers are updated inside startTransition', async () => { |
| 32 | const subs = new Set(); |
| 33 | const useUserSpaceSubscription = () => { |
| 34 | const setState = useState(0)[1]; |
| 35 | subs.add(setState); |
| 36 | }; |
| 37 | |
| 38 | let triggerHookTransition; |
| 39 | |
| 40 | const Component = ({level}) => { |
| 41 | useUserSpaceSubscription(); |
| 42 | if (level === 0) { |
| 43 | triggerHookTransition = useTransition()[1]; |
| 44 | } |
| 45 | if (level < SUSPICIOUS_NUMBER_OF_FIBERS_UPDATED) { |
| 46 | return <Component level={level + 1} />; |
| 47 | } |
| 48 | return null; |
| 49 | }; |
| 50 | |
| 51 | await act(() => { |
| 52 | ReactTestRenderer.create(<Component level={0} />, { |
| 53 | unstable_isConcurrent: true, |
| 54 | }); |
| 55 | }); |
| 56 | |
| 57 | await act(() => { |
| 58 | React.startTransition(() => { |
| 59 | subs.forEach(setState => { |
| 60 | setState(state => state + 1); |
| 61 | }); |
| 62 | }); |
| 63 | }); |
| 64 | assertConsoleWarnDev([ |
| 65 | 'Detected a large number of updates inside startTransition. ' + |
| 66 | 'If this is due to a subscription please re-write it to use React provided hooks. ' + |
| 67 | 'Otherwise concurrent mode guarantees are off the table.', |
| 68 | ]); |
| 69 | |
| 70 | await act(() => { |
| 71 | triggerHookTransition(() => { |
| 72 | subs.forEach(setState => { |
| 73 | setState(state => state + 1); |
| 74 | }); |
| 75 | }); |
| 76 | }); |
| 77 | assertConsoleWarnDev([ |
| 78 | 'Detected a large number of updates inside startTransition. ' + |
| 79 | 'If this is due to a subscription please re-write it to use React provided hooks. ' + |
| 80 | 'Otherwise concurrent mode guarantees are off the table.', |
| 81 | ]); |
| 82 | }); |
| 83 | }); |