|
| 1 | +/** |
| 2 | + * @vitest-environment jsdom |
| 3 | + */ |
| 4 | +import { act } from 'react' |
| 5 | +import { createRoot } from 'react-dom/client' |
| 6 | +import { renderToStaticMarkup } from 'react-dom/server' |
| 7 | +import { describe, expect, it, vi } from 'vitest' |
| 8 | +import { CopyCodeButton } from './copy-code-button' |
| 9 | + |
| 10 | +describe('CopyCodeButton', () => { |
| 11 | + it.each(['default', 'code-header'] as const)( |
| 12 | + 'names the icon-only button in the %s appearance', |
| 13 | + (appearance) => { |
| 14 | + const markup = renderToStaticMarkup(<CopyCodeButton code='example' appearance={appearance} />) |
| 15 | + |
| 16 | + expect(markup).toContain('aria-label="Copy code"') |
| 17 | + expect(markup).toContain('type="button"') |
| 18 | + } |
| 19 | + ) |
| 20 | + |
| 21 | + it('copies code, swaps to the check icon, and keeps its accessible name', async () => { |
| 22 | + ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true |
| 23 | + const writeText = vi.fn().mockResolvedValue(undefined) |
| 24 | + const originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard') |
| 25 | + Object.defineProperty(navigator, 'clipboard', { |
| 26 | + configurable: true, |
| 27 | + value: { writeText }, |
| 28 | + }) |
| 29 | + const host = document.createElement('div') |
| 30 | + document.body.appendChild(host) |
| 31 | + const root = createRoot(host) |
| 32 | + |
| 33 | + try { |
| 34 | + await act(async () => { |
| 35 | + root.render(<CopyCodeButton code='example' appearance='code-header' />) |
| 36 | + }) |
| 37 | + const button = host.querySelector('button') |
| 38 | + expect(button?.getAttribute('aria-label')).toBe('Copy code') |
| 39 | + expect(button?.querySelector('svg rect')).not.toBeNull() |
| 40 | + |
| 41 | + await act(async () => { |
| 42 | + button?.click() |
| 43 | + }) |
| 44 | + |
| 45 | + expect(writeText).toHaveBeenCalledExactlyOnceWith('example') |
| 46 | + expect(button?.querySelector('svg rect')).toBeNull() |
| 47 | + expect(button?.querySelector('svg path')).not.toBeNull() |
| 48 | + expect(button?.getAttribute('aria-label')).toBe('Copy code') |
| 49 | + } finally { |
| 50 | + await act(async () => root.unmount()) |
| 51 | + host.remove() |
| 52 | + if (originalClipboard) Object.defineProperty(navigator, 'clipboard', originalClipboard) |
| 53 | + else Reflect.deleteProperty(navigator, 'clipboard') |
| 54 | + } |
| 55 | + }) |
| 56 | +}) |
0 commit comments