|
| 1 | +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; |
| 2 | +import { initializeTrrack, Registry } from '@trrack/core'; |
| 3 | +import { useEffect, useMemo, useState } from 'react'; |
| 4 | + |
| 5 | +function setup() { |
| 6 | + const registry = Registry.create<'count'>(); |
| 7 | + const add = registry.register( |
| 8 | + 'add', |
| 9 | + (state: { count: number }, amount: number) => { |
| 10 | + state.count += amount; |
| 11 | + }, |
| 12 | + { |
| 13 | + eventType: 'count', |
| 14 | + } |
| 15 | + ); |
| 16 | + |
| 17 | + const trrack = initializeTrrack({ |
| 18 | + registry, |
| 19 | + initialState: { count: 0 }, |
| 20 | + }); |
| 21 | + |
| 22 | + return { trrack, add }; |
| 23 | +} |
| 24 | + |
| 25 | +function BackendConsumer() { |
| 26 | + const { trrack, add } = useMemo(() => setup(), []); |
| 27 | + const [backend, setBackend] = useState(() => trrack.graph.backend); |
| 28 | + |
| 29 | + useEffect(() => { |
| 30 | + return trrack.currentChange(() => { |
| 31 | + setBackend(trrack.graph.backend); |
| 32 | + }); |
| 33 | + }, [trrack]); |
| 34 | + |
| 35 | + return ( |
| 36 | + <div> |
| 37 | + <button |
| 38 | + onClick={() => { |
| 39 | + void trrack.apply('Add', add(1)); |
| 40 | + }} |
| 41 | + > |
| 42 | + Add |
| 43 | + </button> |
| 44 | + <div data-testid="node-count">{Object.keys(backend.nodes).length}</div> |
| 45 | + <div data-testid="current-id">{backend.current}</div> |
| 46 | + </div> |
| 47 | + ); |
| 48 | +} |
| 49 | + |
| 50 | +describe('React backend subscriptions', () => { |
| 51 | + it('rerenders when currentChange listeners set graph.backend into React state', async () => { |
| 52 | + render(<BackendConsumer />); |
| 53 | + |
| 54 | + const initialCurrentId = screen.getByTestId('current-id').textContent; |
| 55 | + expect(screen.getByTestId('node-count').textContent).toBe('1'); |
| 56 | + |
| 57 | + fireEvent.click(screen.getByRole('button', { name: 'Add' })); |
| 58 | + |
| 59 | + await waitFor(() => { |
| 60 | + expect(screen.getByTestId('node-count').textContent).toBe('2'); |
| 61 | + }); |
| 62 | + |
| 63 | + expect(screen.getByTestId('current-id').textContent).not.toBe( |
| 64 | + initialCurrentId |
| 65 | + ); |
| 66 | + }); |
| 67 | +}); |
0 commit comments