|
| 1 | +import {render, screen} from '@testing-library/react' |
| 2 | +import Field from '../Field' |
| 3 | +import Form from '../Form' |
| 4 | +import ArrayField from './index' |
| 5 | +import {FieldProps} from '../types' |
| 6 | +import '@testing-library/jest-dom' |
| 7 | + |
| 8 | +jest.useFakeTimers() |
| 9 | + |
| 10 | +function DummyInput(props: FieldProps) { |
| 11 | + return ( |
| 12 | + <input |
| 13 | + value={props.value || ''} |
| 14 | + onChange={e => props.onChange(e.target.value)} |
| 15 | + /> |
| 16 | + ) |
| 17 | +} |
| 18 | + |
| 19 | +test('autoAddItem renders an empty item when value is empty', () => { |
| 20 | + const {container} = render( |
| 21 | + <Form> |
| 22 | + <Field fieldName="items" type={ArrayField} autoAddItem> |
| 23 | + <Field fieldName="name" type={DummyInput} /> |
| 24 | + </Field> |
| 25 | + </Form>, |
| 26 | + ) |
| 27 | + expect(container.querySelectorAll('input')).toHaveLength(1) |
| 28 | +}) |
| 29 | + |
| 30 | +test('renderProps provides the current index', () => { |
| 31 | + render( |
| 32 | + <Form state={{items: [{}]}}> |
| 33 | + <Field fieldName="items" type={ArrayField} renderProps> |
| 34 | + {index => <div data-testid={`item-${index}`}>Item {index}</div>} |
| 35 | + </Field> |
| 36 | + </Form>, |
| 37 | + ) |
| 38 | + expect(screen.getByTestId('item-0')).toBeInTheDocument() |
| 39 | +}) |
| 40 | + |
| 41 | +test('renderItem customizes each item element', () => { |
| 42 | + render( |
| 43 | + <Form state={{items: [{name: 'A'}]}}> |
| 44 | + <Field |
| 45 | + fieldName="items" |
| 46 | + type={ArrayField} |
| 47 | + renderItem={(item, i) => <div data-testid={`custom-${i}`}>{item.name}</div>} |
| 48 | + /> |
| 49 | + </Form>, |
| 50 | + ) |
| 51 | + expect(screen.getByTestId('custom-0')).toHaveTextContent('A') |
| 52 | +}) |
| 53 | + |
| 54 | +test('honors showAddButton and custom addLabel', () => { |
| 55 | + const {container} = render( |
| 56 | + <Form> |
| 57 | + <Field fieldName="items" type={ArrayField} showAddButton={false} addLabel="Plus"> |
| 58 | + <Field fieldName="name" type={DummyInput} /> |
| 59 | + </Field> |
| 60 | + </Form>, |
| 61 | + ) |
| 62 | + expect(screen.queryByText('Plus')).not.toBeInTheDocument() |
| 63 | + expect(container.querySelector('.srf_addButton')).not.toBeInTheDocument() |
| 64 | +}) |
| 65 | + |
| 66 | +test('honors showRemoveButton and custom removeLabel', () => { |
| 67 | + const {container} = render( |
| 68 | + <Form state={{items: [{}]}}> |
| 69 | + <Field |
| 70 | + fieldName="items" |
| 71 | + type={ArrayField} |
| 72 | + showRemoveButton={false} |
| 73 | + removeLabel="Del" |
| 74 | + > |
| 75 | + <Field fieldName="name" type={DummyInput} /> |
| 76 | + </Field> |
| 77 | + </Form>, |
| 78 | + ) |
| 79 | + expect(screen.queryByText('Del')).not.toBeInTheDocument() |
| 80 | + expect(container.querySelector('.srf_removeButton')).not.toBeInTheDocument() |
| 81 | +}) |
0 commit comments