|
| 1 | +let React; |
| 2 | +let ReactNoop; |
| 3 | +let Scheduler; |
| 4 | +let useState; |
| 5 | +let useEffect; |
| 6 | + |
| 7 | +describe('ReactFlushSync', () => { |
| 8 | + beforeEach(() => { |
| 9 | + jest.resetModules(); |
| 10 | + |
| 11 | + React = require('react'); |
| 12 | + ReactNoop = require('react-noop-renderer'); |
| 13 | + Scheduler = require('scheduler'); |
| 14 | + useState = React.useState; |
| 15 | + useEffect = React.useEffect; |
| 16 | + }); |
| 17 | + |
| 18 | + function Text({text}) { |
| 19 | + Scheduler.unstable_yieldValue(text); |
| 20 | + return text; |
| 21 | + } |
| 22 | + |
| 23 | + // @gate experimental || !enableSyncDefaultUpdates |
| 24 | + test('changes priority of updates in useEffect', async () => { |
| 25 | + function App() { |
| 26 | + const [syncState, setSyncState] = useState(0); |
| 27 | + const [state, setState] = useState(0); |
| 28 | + useEffect(() => { |
| 29 | + if (syncState !== 1) { |
| 30 | + setState(1); |
| 31 | + ReactNoop.flushSync(() => setSyncState(1)); |
| 32 | + } |
| 33 | + }, [syncState, state]); |
| 34 | + return <Text text={`${syncState}, ${state}`} />; |
| 35 | + } |
| 36 | + |
| 37 | + const root = ReactNoop.createRoot(); |
| 38 | + await ReactNoop.act(async () => { |
| 39 | + if (gate(flags => flags.enableSyncDefaultUpdates)) { |
| 40 | + React.unstable_startTransition(() => { |
| 41 | + root.render(<App />); |
| 42 | + }); |
| 43 | + } else { |
| 44 | + root.render(<App />); |
| 45 | + } |
| 46 | + // This will yield right before the passive effect fires |
| 47 | + expect(Scheduler).toFlushUntilNextPaint(['0, 0']); |
| 48 | + |
| 49 | + // The passive effect will schedule a sync update and a normal update. |
| 50 | + // They should commit in two separate batches. First the sync one. |
| 51 | + expect(() => { |
| 52 | + expect(Scheduler).toFlushUntilNextPaint(['1, 0']); |
| 53 | + }).toErrorDev('flushSync was called from inside a lifecycle method'); |
| 54 | + |
| 55 | + // The remaining update is not sync |
| 56 | + ReactNoop.flushSync(); |
| 57 | + expect(Scheduler).toHaveYielded([]); |
| 58 | + |
| 59 | + // Now flush it. |
| 60 | + expect(Scheduler).toFlushUntilNextPaint(['1, 1']); |
| 61 | + }); |
| 62 | + expect(root).toMatchRenderedOutput('1, 1'); |
| 63 | + }); |
| 64 | +}); |
0 commit comments