|
| 1 | +/** @vitest-environment jsdom */ |
| 2 | +import { act, createRef } from 'react' |
| 3 | +import { AddRowButton } from '@sim/emcn' |
| 4 | +import { createRoot, type Root } from 'react-dom/client' |
| 5 | +import { afterEach, describe, expect, it, vi } from 'vitest' |
| 6 | + |
| 7 | +let root: Root | null = null |
| 8 | +let container: HTMLDivElement | null = null |
| 9 | + |
| 10 | +afterEach(() => { |
| 11 | + if (root) act(() => root?.unmount()) |
| 12 | + container?.remove() |
| 13 | + root = null |
| 14 | + container = null |
| 15 | +}) |
| 16 | + |
| 17 | +describe('AddRowButton', () => { |
| 18 | + it('forwards its ref and action, honors disabled, and preserves native form submission', () => { |
| 19 | + ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true |
| 20 | + container = document.createElement('div') |
| 21 | + document.body.appendChild(container) |
| 22 | + root = createRoot(container) |
| 23 | + const ref = createRef<HTMLButtonElement>() |
| 24 | + const onClick = vi.fn() |
| 25 | + const onSubmit = vi.fn((event) => event.preventDefault()) |
| 26 | + const render = (disabled: boolean) => ( |
| 27 | + <form onSubmit={onSubmit}> |
| 28 | + <AddRowButton ref={ref} onClick={onClick} disabled={disabled}> |
| 29 | + Add filter condition |
| 30 | + </AddRowButton> |
| 31 | + </form> |
| 32 | + ) |
| 33 | + act(() => root?.render(render(false))) |
| 34 | + const button = ref.current! |
| 35 | + expect(button).toBe(container.querySelector('button')) |
| 36 | + expect(button.textContent).toBe('Add filter condition') |
| 37 | + expect(button.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true') |
| 38 | + act(() => button.click()) |
| 39 | + expect(onClick).toHaveBeenCalledOnce() |
| 40 | + expect(onSubmit).toHaveBeenCalledOnce() |
| 41 | + |
| 42 | + act(() => root?.render(render(true))) |
| 43 | + expect(button.disabled).toBe(true) |
| 44 | + act(() => button.click()) |
| 45 | + expect(onClick).toHaveBeenCalledOnce() |
| 46 | + }) |
| 47 | +}) |
0 commit comments