|
| 1 | +import { render, screen } from '@testing-library/react' |
| 2 | +import userEvent from '@testing-library/user-event' |
| 3 | +import { describe, expect, it, vi } from 'vitest' |
| 4 | +import type { MouseEvent } from 'react' |
| 5 | + |
| 6 | +import { Tag } from './Tag' |
| 7 | + |
| 8 | +describe('Tag', () => { |
| 9 | + it('renders tag content', () => { |
| 10 | + render(<Tag color="success">Active</Tag>) |
| 11 | + |
| 12 | + expect(screen.getByText('Active')).toBeInTheDocument() |
| 13 | + expect(screen.queryByRole('button')).not.toBeInTheDocument() |
| 14 | + }) |
| 15 | + |
| 16 | + it('hides after the close button is clicked', async () => { |
| 17 | + const user = userEvent.setup() |
| 18 | + const onClose = vi.fn() |
| 19 | + |
| 20 | + render( |
| 21 | + <Tag closable onClose={onClose}> |
| 22 | + Removable |
| 23 | + </Tag>, |
| 24 | + ) |
| 25 | + |
| 26 | + await user.click(screen.getByRole('button', { name: 'Close tag' })) |
| 27 | + |
| 28 | + expect(onClose).toHaveBeenCalledTimes(1) |
| 29 | + expect(onClose.mock.calls[0]?.[0]).toHaveProperty('type', 'click') |
| 30 | + expect(screen.queryByText('Removable')).not.toBeInTheDocument() |
| 31 | + }) |
| 32 | + |
| 33 | + it('keeps the tag visible when close is prevented', async () => { |
| 34 | + const user = userEvent.setup() |
| 35 | + const onClose = vi.fn((event: MouseEvent<HTMLButtonElement>) => { |
| 36 | + event.preventDefault() |
| 37 | + }) |
| 38 | + |
| 39 | + render( |
| 40 | + <Tag closable onClose={onClose}> |
| 41 | + Locked |
| 42 | + </Tag>, |
| 43 | + ) |
| 44 | + |
| 45 | + await user.click(screen.getByRole('button', { name: 'Close tag' })) |
| 46 | + |
| 47 | + expect(onClose).toHaveBeenCalledTimes(1) |
| 48 | + expect(screen.getByText('Locked')).toBeInTheDocument() |
| 49 | + }) |
| 50 | + |
| 51 | + it('supports custom close icon and accessible name', () => { |
| 52 | + render( |
| 53 | + <Tag closable closeIcon="Remove" closeAriaLabel="Remove tag"> |
| 54 | + Custom |
| 55 | + </Tag>, |
| 56 | + ) |
| 57 | + |
| 58 | + const closeButton = screen.getByRole('button', { name: 'Remove tag' }) |
| 59 | + expect(closeButton).toHaveTextContent('Remove') |
| 60 | + }) |
| 61 | +}) |
0 commit comments