-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathArrayInput.spec.tsx
More file actions
546 lines (483 loc) · 20.3 KB
/
ArrayInput.spec.tsx
File metadata and controls
546 lines (483 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
import * as React from 'react';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {
RecordContextProvider,
ResourceContextProvider,
testDataProvider,
useArrayInput,
} from 'ra-core';
import { AdminContext } from '../../AdminContext';
import { SimpleForm } from '../../form';
import { NumberInput } from '../NumberInput';
import { TextInput } from '../TextInput';
import { ArrayInput } from './ArrayInput';
import { SimpleFormIterator } from './SimpleFormIterator';
import { useFormContext } from 'react-hook-form';
import {
GlobalValidation,
ScalarWithValidation,
ValidationInFormTab,
NestedInline,
WithReferenceField,
NestedInlineNoTranslation,
Validation,
Focus,
Reset,
ConditionalArrayInputValidationContent,
} from './ArrayInput.stories';
describe('<ArrayInput />', () => {
it('should pass array functions to child', async () => {
let childProps;
const MockChild = () => {
childProps = useArrayInput();
return null;
};
render(
<AdminContext dataProvider={testDataProvider()}>
<ResourceContextProvider value="posts">
<SimpleForm
onSubmit={jest.fn}
defaultValues={{
foo: [{ id: 1 }, { id: 2 }],
}}
>
<ArrayInput source="foo">
<MockChild />
</ArrayInput>
</SimpleForm>
</ResourceContextProvider>
</AdminContext>
);
await waitFor(() => {
expect(childProps.fields.length).toEqual(2);
});
});
it('should not create any section subform when the value is undefined', () => {
const { baseElement } = render(
<AdminContext dataProvider={testDataProvider()}>
<ResourceContextProvider value="posts">
<SimpleForm onSubmit={jest.fn}>
<ArrayInput source="foo">
<SimpleFormIterator />
</ArrayInput>
</SimpleForm>
</ResourceContextProvider>
</AdminContext>
);
expect(baseElement.querySelectorAll('section')).toHaveLength(0);
});
it('should create one section subform per value in the array', async () => {
const { baseElement } = render(
<AdminContext dataProvider={testDataProvider()}>
<ResourceContextProvider value="bar">
<SimpleForm
onSubmit={jest.fn}
defaultValues={{
foo: [{}, {}, {}],
}}
>
<ArrayInput source="foo">
<SimpleFormIterator />
</ArrayInput>
</SimpleForm>
</ResourceContextProvider>
</AdminContext>
);
await waitFor(() => {
expect(
baseElement.querySelectorAll('.RaSimpleFormIterator-line')
).toHaveLength(3);
});
});
it('should render each input once per value in the array', () => {
render(
<AdminContext dataProvider={testDataProvider()}>
<ResourceContextProvider value="bar">
<SimpleForm
onSubmit={jest.fn}
defaultValues={{
arr: [
{ id: 123, foo: 'bar' },
{ id: 456, foo: 'baz' },
],
}}
>
<ArrayInput source="arr">
<SimpleFormIterator>
<NumberInput source="id" />
<TextInput source="foo" />
</SimpleFormIterator>
</ArrayInput>
</SimpleForm>
</ResourceContextProvider>
</AdminContext>
);
expect(
screen.queryAllByLabelText('resources.bar.fields.arr.id')
).toHaveLength(2);
expect(
screen
.queryAllByLabelText('resources.bar.fields.arr.id')
.map(input => (input as HTMLInputElement).value)
).toEqual(['123', '456']);
expect(
screen.queryAllByLabelText('resources.bar.fields.arr.foo')
).toHaveLength(2);
expect(
screen
.queryAllByLabelText('resources.bar.fields.arr.foo')
.map(input => (input as HTMLInputElement).value)
).toEqual(['bar', 'baz']);
});
it('should apply validation to both itself and its inner inputs', async () => {
render(<Validation />);
fireEvent.click(await screen.findByLabelText('Add'));
fireEvent.click(screen.getByText('Save'));
await waitFor(() => {
// The two inputs in each item are required
expect(screen.queryAllByText('Required')).toHaveLength(2);
});
fireEvent.click(screen.getAllByLabelText('Remove')[2]);
fireEvent.click(screen.getAllByLabelText('Remove')[1]);
fireEvent.click(screen.getByText('Save'));
await screen.findByText('You need two authors at minimum');
});
it('should maintain its form value after having been unmounted', async () => {
let value, setArrayInputVisible;
const MyArrayInput = () => {
const [visible, setVisible] = React.useState(true);
const { getValues } = useFormContext();
value = jest.fn(() => getValues('arr'));
value();
setArrayInputVisible = setVisible;
return visible ? (
<ArrayInput source="arr">
<SimpleFormIterator>
<TextInput source="id" />
<TextInput source="foo" />
</SimpleFormIterator>
</ArrayInput>
) : null;
};
render(
<AdminContext dataProvider={testDataProvider()}>
<ResourceContextProvider value="bar">
<SimpleForm
onSubmit={jest.fn}
defaultValues={{
arr: [
{ id: 1, foo: 'bar' },
{ id: 2, foo: 'baz' },
],
}}
>
<MyArrayInput />
</SimpleForm>
</ResourceContextProvider>
</AdminContext>
);
await waitFor(() => {
expect(value.mock.results[0].value).toEqual([
{ id: 1, foo: 'bar' },
{ id: 2, foo: 'baz' },
]);
});
setArrayInputVisible(false);
await waitFor(() => {
expect(value.mock.results[0].value).toEqual([
{ id: 1, foo: 'bar' },
{ id: 2, foo: 'baz' },
]);
});
});
it('should not clear errors of children when unmounted', async () => {
let setArrayInputVisible;
const MyArrayInput = () => {
const [visible, setVisible] = React.useState(true);
setArrayInputVisible = setVisible;
return visible ? (
<ArrayInput source="arr">
<SimpleFormIterator>
<TextInput source="id" />
<TextInput source="foo" />
</SimpleFormIterator>
</ArrayInput>
) : null;
};
render(
<AdminContext dataProvider={testDataProvider()}>
<ResourceContextProvider value="bar">
<SimpleForm
onSubmit={jest.fn}
defaultValues={{
arr: [
{ id: 1, foo: 'bar' },
{ id: 2, foo: 'baz' },
],
}}
validate={() => ({
arr: [{ foo: 'Must be "baz"' }, {}],
})}
>
<MyArrayInput />
</SimpleForm>
</ResourceContextProvider>
</AdminContext>
);
// change one input to enable the SaveButton (which is disabled when the form is pristine)
fireEvent.change(
screen.getAllByLabelText('resources.bar.fields.arr.id')[0],
{
target: { value: '42' },
}
);
fireEvent.click(await screen.findByLabelText('ra.action.save'));
await screen.findByText('Must be "baz"');
setArrayInputVisible(false);
await waitFor(() => {
expect(screen.queryByText('Must be "baz"')).toBeNull();
});
// ensure errors are still there after re-mount
setArrayInputVisible(true);
await screen.findByText('Must be "baz"');
});
it('should allow to have a helperText', () => {
render(
<AdminContext dataProvider={testDataProvider()}>
<ResourceContextProvider value="bar">
<SimpleForm onSubmit={jest.fn}>
<ArrayInput source="foo" helperText="test helper text">
<SimpleFormIterator />
</ArrayInput>
</SimpleForm>
</ResourceContextProvider>
</AdminContext>
);
expect(screen.queryByText('test helper text')).not.toBeNull();
});
it('should not display a root-level array error immediately when mounted in onChange mode', async () => {
render(
<AdminContext dataProvider={testDataProvider()}>
<ResourceContextProvider value="books">
<SimpleForm mode="onChange" onSubmit={jest.fn()}>
<ConditionalArrayInputValidationContent />
</SimpleForm>
</ResourceContextProvider>
</AdminContext>
);
fireEvent.click(screen.getByText('Show array input'));
await screen.findByLabelText('ra.action.add');
expect(screen.queryByText('ra.validation.required')).toBeNull();
fireEvent.click(await screen.findByLabelText('ra.action.add'));
fireEvent.click(await screen.findByLabelText('ra.action.remove'));
await screen.findByText('ra.validation.required');
fireEvent.click(screen.getByText('ra.action.save'));
await screen.findByText('ra.validation.required');
});
it('should update the form state to dirty, and allow submit, on updating an array input with default value', async () => {
render(
<AdminContext dataProvider={testDataProvider()}>
<ResourceContextProvider value="posts">
{/**
* RecordContextProvider - required to mimic instantiating a form with default data so that the it reset by
* a react admin lifecycle and giving a non dirty form state. This in turn means the submit button is disabled on first render.
*/}
<RecordContextProvider value={{ foo: 'bar' }}>
<SimpleForm onSubmit={jest.fn}>
<ArrayInput
source="arr"
defaultValue={[{ id: 'foo' }]}
>
<SimpleFormIterator>
<TextInput source="id" />
</SimpleFormIterator>
</ArrayInput>
</SimpleForm>
</RecordContextProvider>
</ResourceContextProvider>
</AdminContext>
);
const submitButton = screen
.getByLabelText('ra.action.save')
.closest('button');
await waitFor(() => {
expect(submitButton?.disabled).toBe(true);
});
const firstArrayInput = screen.getByDisplayValue('foo');
userEvent.type(firstArrayInput, 'bar');
await waitFor(() => {
expect(submitButton?.disabled).toBe(false);
});
});
it('should correctly update validation state after removing an item', async () => {
render(<ScalarWithValidation />);
await screen.findByDisplayValue('classic');
fireEvent.click(await screen.findByLabelText('Add'));
fireEvent.click(await screen.findByText('Save'));
await screen.findByText('Required');
fireEvent.click((await screen.findAllByLabelText('Remove'))[0]);
await waitFor(() => {
expect(screen.queryByText('Required')).toBeNull();
});
});
describe('used within a form with global validation', () => {
it('should display an error if the array is required and empty', async () => {
render(<GlobalValidation />);
await screen.findByDisplayValue('Leo Tolstoy');
const RemoveButtons = screen.getAllByLabelText('Remove');
fireEvent.click(RemoveButtons[1]);
fireEvent.click(RemoveButtons[0]);
await waitFor(() => {
expect(screen.queryAllByLabelText('Remove')).toHaveLength(0);
});
await screen.findByText('Required');
const SaveButton = screen.getByText('Save');
fireEvent.click(SaveButton);
await screen.findByText(
'The form is not valid. Please check for errors'
);
});
it('should display an error if one of the required field is empty', async () => {
render(<GlobalValidation />);
await screen.findByDisplayValue('Leo Tolstoy');
fireEvent.change(screen.queryAllByLabelText('Name *')[0], {
target: { value: '' },
});
const SaveButton = screen.getByText('Save');
fireEvent.click(SaveButton);
await screen.findByText('A name is required');
});
it('should clear the error right after it has been fixed after submission', async () => {
render(<GlobalValidation />);
await screen.findByDisplayValue('Leo Tolstoy');
fireEvent.change(screen.queryAllByLabelText('Name *')[0], {
target: { value: '' },
});
const SaveButton = screen.getByText('Save');
fireEvent.click(SaveButton);
await screen.findByText('A name is required');
fireEvent.change(screen.queryAllByLabelText('Name *')[0], {
target: { value: 'Leo Dicaprio' },
});
await waitFor(() => {
expect(screen.queryByText('A name is required')).toBeNull();
});
});
it('should turn form tab in red if the array is required and empty', async () => {
render(<ValidationInFormTab />);
userEvent.type(screen.getByLabelText('Title'), 'a');
await screen.findByDisplayValue('a');
fireEvent.click(screen.getByText('Save'));
const formTab = await screen.findByText('Main');
await screen.findByText('Required');
await waitFor(() => {
expect(
formTab.classList.contains('RaTabbedForm-errorTabButton')
).toBe(true);
});
expect(formTab.classList.contains('error')).toBe(true);
});
});
it('should support nested ArrayInput and inputs that set up SourceContexts', async () => {
render(<NestedInline />);
await screen.findByDisplayValue('Office Jeans');
await screen.findByDisplayValue('Jean de bureau');
await screen.findByDisplayValue('45.99');
expect(
await screen.findAllByDisplayValue('For you my love')
).toHaveLength(2);
expect(
await screen.findAllByDisplayValue('Pour toi mon amour')
).toHaveLength(2);
});
it('should support fields', async () => {
render(<WithReferenceField />);
await screen.findByText('Russia');
await screen.findByText('Italy');
});
it('should correctly set inputs and field labels even nested', async () => {
render(<NestedInlineNoTranslation />);
await screen.findByLabelText('resources.orders.fields.customer');
await screen.findByLabelText('resources.orders.fields.date');
await screen.findByText('resources.orders.fields.items');
await screen.findAllByText('resources.orders.fields.items.name');
await screen.findAllByLabelText('resources.orders.fields.items.price');
});
it('should focus the first input of a newly added item', async () => {
const { rerender } = render(<Focus input="text" />);
fireEvent.click(await screen.findByLabelText('Add'));
await waitFor(() => {
expect(document.activeElement).toBe(
screen.getAllByLabelText('Name')[2]
);
});
rerender(<Focus input="date" />);
fireEvent.click(await screen.findByLabelText('Add'));
await waitFor(() => {
expect(document.activeElement).toBe(
screen.getAllByLabelText('Added at')[2]
);
});
rerender(<Focus input="datetime" />);
fireEvent.click(await screen.findByLabelText('Add'));
await waitFor(() => {
expect(document.activeElement).toBe(
screen.getAllByLabelText('Added at')[2]
);
});
rerender(<Focus input="autocomplete" />);
fireEvent.click(await screen.findByLabelText('Add'));
await waitFor(() => {
expect(document.activeElement).toBe(
screen.getAllByLabelText('Role')[2]
);
});
});
describe('should empty the input on form reset', () => {
it('should remove a filled line twice', async () => {
render(<Reset />);
expect(screen.queryAllByRole('listitem')).toHaveLength(0);
fireEvent.click(await screen.findByRole('button', { name: 'Add' }));
fireEvent.change(screen.getByLabelText('Name'), {
target: { value: 'Leo Tolstoy' },
});
fireEvent.change(screen.getByLabelText('Role'), {
target: { value: 'Writer' },
});
expect(screen.queryAllByRole('listitem')).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: 'Reset' }));
await waitFor(() => {
expect(screen.queryAllByRole('listitem')).toHaveLength(0);
});
fireEvent.click(await screen.findByRole('button', { name: 'Add' }));
fireEvent.change(screen.getByLabelText('Name'), {
target: { value: 'Leo Tolstoy' },
});
fireEvent.change(screen.getByLabelText('Role'), {
target: { value: 'Writer' },
});
expect(screen.queryAllByRole('listitem')).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: 'Reset' }));
await waitFor(() => {
expect(screen.queryAllByRole('listitem')).toHaveLength(0);
});
});
it('should remove an empty line twice', async () => {
render(<Reset />);
expect(screen.queryAllByRole('listitem')).toHaveLength(0);
fireEvent.click(await screen.findByRole('button', { name: 'Add' }));
expect(screen.queryAllByRole('listitem')).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: 'Reset' }));
await waitFor(() => {
expect(screen.queryAllByRole('listitem')).toHaveLength(0);
});
fireEvent.click(await screen.findByRole('button', { name: 'Add' }));
expect(screen.queryAllByRole('listitem')).toHaveLength(1);
fireEvent.click(screen.getByRole('button', { name: 'Reset' }));
await waitFor(() => {
expect(screen.queryAllByRole('listitem')).toHaveLength(0);
});
});
});
});