|
| 1 | +/** |
| 2 | + * @vitest-environment jsdom |
| 3 | + */ |
| 4 | +import { act } from 'react' |
| 5 | +import { createRoot, type Root } from 'react-dom/client' |
| 6 | +import { afterEach, describe, expect, it, vi } from 'vitest' |
| 7 | +import { FieldDisclosure } from './field-divider' |
| 8 | + |
| 9 | +let root: Root | null = null |
| 10 | +let container: HTMLDivElement | null = null |
| 11 | + |
| 12 | +afterEach(() => { |
| 13 | + act(() => root?.unmount()) |
| 14 | + container?.remove() |
| 15 | + root = null |
| 16 | + container = null |
| 17 | +}) |
| 18 | + |
| 19 | +describe('FieldDisclosure', () => { |
| 20 | + it('leaves expansion to the caller and does not submit its surrounding form', () => { |
| 21 | + const onClick = vi.fn() |
| 22 | + const onSubmit = vi.fn((event) => event.preventDefault()) |
| 23 | + container = document.createElement('div') |
| 24 | + document.body.appendChild(container) |
| 25 | + root = createRoot(container) |
| 26 | + const render = (expanded: boolean, disabled = false) => ( |
| 27 | + <form onSubmit={onSubmit}> |
| 28 | + <FieldDisclosure |
| 29 | + expanded={expanded} |
| 30 | + disabled={disabled} |
| 31 | + onClick={onClick} |
| 32 | + aria-controls='additional-fields' |
| 33 | + > |
| 34 | + {expanded ? 'Hide additional fields' : 'Show additional fields'} |
| 35 | + </FieldDisclosure> |
| 36 | + <div id='additional-fields' hidden={!expanded}> |
| 37 | + Additional fields |
| 38 | + </div> |
| 39 | + </form> |
| 40 | + ) |
| 41 | + act(() => root?.render(render(false))) |
| 42 | + const button = container.querySelector('button')! |
| 43 | + expect(button.getAttribute('aria-expanded')).toBe('false') |
| 44 | + expect(button.getAttribute('aria-controls')).toBe('additional-fields') |
| 45 | + act(() => { |
| 46 | + button.focus() |
| 47 | + button.click() |
| 48 | + }) |
| 49 | + expect(document.activeElement).toBe(button) |
| 50 | + expect(onClick).toHaveBeenCalledTimes(1) |
| 51 | + expect(onSubmit).not.toHaveBeenCalled() |
| 52 | + expect(button.getAttribute('aria-expanded')).toBe('false') |
| 53 | + |
| 54 | + act(() => root?.render(render(true))) |
| 55 | + expect(button.getAttribute('aria-expanded')).toBe('true') |
| 56 | + expect(button.textContent).toBe('Hide additional fields') |
| 57 | + expect(container.querySelector<HTMLElement>('#additional-fields')?.hidden).toBe(false) |
| 58 | + |
| 59 | + act(() => root?.render(render(true, true))) |
| 60 | + act(() => button.click()) |
| 61 | + expect(onClick).toHaveBeenCalledTimes(1) |
| 62 | + expect(onSubmit).not.toHaveBeenCalled() |
| 63 | + }) |
| 64 | +}) |
0 commit comments