-
-
Notifications
You must be signed in to change notification settings - Fork 629
Expand file tree
/
Copy pathModuleForm.test.tsx
More file actions
972 lines (840 loc) · 28.1 KB
/
ModuleForm.test.tsx
File metadata and controls
972 lines (840 loc) · 28.1 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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
/**
* @file Comprehensive unit tests for the ModuleForm component
* Targeting 90-95% code coverage.
*/
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import '@testing-library/jest-dom'
import React from 'react'
import ModuleForm, { ProjectSelector } from 'components/ModuleForm'
// Mock next/navigation
const mockBack = jest.fn()
jest.mock('next/navigation', () => ({
useRouter: () => ({
back: mockBack,
}),
}))
// Mock apollo client hooks
const mockQuery = jest.fn()
jest.mock('@apollo/client/react', () => ({
...jest.requireActual('@apollo/client/react'),
useApolloClient: () => ({
query: mockQuery,
}),
}))
// Mock heroui components
jest.mock('@heroui/react', () => ({
Autocomplete: ({
children,
inputValue,
_selectedKey,
onInputChange,
onSelectionChange,
isInvalid,
errorMessage,
isLoading,
label,
id,
}: {
children: React.ReactNode
inputValue?: string
_selectedKey?: string | null
onInputChange?: (value: string) => void
onSelectionChange?: (key: React.Key | Set<React.Key> | 'all') => void
isInvalid?: boolean
errorMessage?: string
isLoading?: boolean
label?: string
id?: string
}) => (
<div data-testid="autocomplete">
<label htmlFor={id}>{label}</label>
<input
id={id}
data-testid="autocomplete-input"
value={inputValue || ''}
data-selected-key={_selectedKey ?? ''}
onChange={(e) => onInputChange?.(e.target.value)}
data-loading={isLoading}
data-invalid={isInvalid}
/>
{errorMessage && <span data-testid="autocomplete-error">{errorMessage}</span>}
<div data-testid="autocomplete-items">{children}</div>
<button
type="button"
data-testid="autocomplete-select-item"
onClick={() => onSelectionChange?.(new Set(['project-1']))}
>
Select Project 1
</button>
<button
type="button"
data-testid="autocomplete-select-all"
onClick={() => onSelectionChange?.('all')}
>
Select All
</button>
<button
type="button"
data-testid="autocomplete-clear"
onClick={() => {
onInputChange?.('')
onSelectionChange?.(null)
}}
>
Clear Selection
</button>
<button
type="button"
data-testid="autocomplete-select-single"
onClick={() => onSelectionChange?.('project-1')}
>
Select Single Key
</button>
</div>
),
AutocompleteItem: ({
children,
textValue,
}: {
children: React.ReactNode
textValue?: string
}) => (
<div data-testid="autocomplete-item" data-text-value={textValue}>
{children}
</div>
),
}))
jest.mock('@heroui/select', () => ({
Select: ({
children,
selectedKeys,
onSelectionChange,
isInvalid,
errorMessage,
label,
id,
}: {
children: React.ReactNode
selectedKeys?: Set<string>
onSelectionChange?: (keys: React.Key | Set<React.Key> | 'all') => void
isInvalid?: boolean
errorMessage?: string
label?: string
id?: string
}) => (
<div data-testid="select" data-invalid={isInvalid}>
<label htmlFor={id}>{label}</label>
<select
id={id}
data-testid="select-input"
value={selectedKeys ? Array.from(selectedKeys)[0] : ''}
onChange={(e) => onSelectionChange?.(new Set([e.target.value]))}
>
<option value="">Select...</option>
{children}
</select>
{errorMessage && <span data-testid="select-error">{errorMessage}</span>}
<button
type="button"
data-testid="select-set"
onClick={() => onSelectionChange?.(new Set(['BEGINNER']))}
>
Set via Set
</button>
<button type="button" data-testid="select-all" onClick={() => onSelectionChange?.('all')}>
Select All
</button>
<button
type="button"
data-testid="select-single"
onClick={() => onSelectionChange?.('INTERMEDIATE')}
>
Select Single
</button>
</div>
),
SelectItem: ({ children }: { children: React.ReactNode }) => (
<option data-testid="select-item">{children}</option>
),
}))
// Mock form components
jest.mock('components/forms/shared/FormButtons', () => ({
FormButtons: ({ loading, submitText }: { loading: boolean; submitText?: string }) => (
<div data-testid="form-buttons">
<button type="button" data-testid="cancel-button">
Cancel
</button>
<button type="submit" disabled={loading} data-testid="submit-button">
{loading ? 'Saving...' : submitText || 'Save'}
</button>
</div>
),
}))
jest.mock('components/forms/shared/FormDateInput', () => ({
FormDateInput: ({
id,
label,
value,
onValueChange,
error,
touched,
}: {
id: string
label: string
value: string
onValueChange: (value: string) => void
error?: string
touched?: boolean
}) => (
<div data-testid={`date-input-${id}`}>
<label htmlFor={id}>{label}</label>
<input
id={id}
type="date"
value={value}
onChange={(e) => onValueChange(e.target.value)}
data-error={error}
data-touched={touched}
/>
{touched && error && <span data-testid={`${id}-error`}>{error}</span>}
</div>
),
}))
jest.mock('components/forms/shared/FormTextarea', () => ({
FormTextarea: ({
id,
label,
value,
onChange,
error,
touched,
}: {
id: string
label: string
value: string
onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
error?: string
touched?: boolean
}) => (
<div data-testid={`textarea-${id}`}>
<label htmlFor={id}>{label}</label>
<textarea id={id} value={value} onChange={onChange} data-testid={`textarea-input-${id}`} />
{touched && error && <span data-testid={`${id}-error`}>{error}</span>}
</div>
),
}))
jest.mock('components/forms/shared/FormTextInput', () => ({
FormTextInput: ({
id,
label,
value,
onValueChange,
error,
touched,
}: {
id: string
label: string
value: string
onValueChange: (value: string) => void
error?: string
touched?: boolean
}) => (
<div data-testid={`text-input-${id}`}>
<label htmlFor={id}>{label}</label>
<input
id={id}
type="text"
value={value}
onChange={(e) => onValueChange(e.target.value)}
data-testid={`input-${id}`}
/>
{touched && error && <span data-testid={`${id}-error`}>{error}</span>}
</div>
),
}))
describe('ModuleForm', () => {
const defaultFormData = {
description: '',
domains: '',
endedAt: '',
experienceLevel: '',
labels: '',
mentorLogins: '',
name: '',
projectId: '',
projectName: '',
startedAt: '',
tags: '',
}
const mockSetFormData = jest.fn()
const mockOnSubmit = jest.fn()
beforeEach(() => {
jest.clearAllMocks()
jest.useFakeTimers()
mockQuery.mockResolvedValue({
data: { searchProjects: [{ id: 'project-1', name: 'Test Project' }] },
})
})
afterEach(() => {
jest.useRealTimers()
})
const renderModuleForm = (props = {}) => {
const defaultProps = {
formData: defaultFormData,
setFormData: mockSetFormData,
onSubmit: mockOnSubmit,
loading: false,
title: 'Create Module',
...props,
}
return render(<ModuleForm {...defaultProps} />)
}
describe('Basic Rendering', () => {
it('renders with title', () => {
renderModuleForm({ title: 'Create New Module' })
expect(screen.getByText('Create New Module')).toBeInTheDocument()
})
it('renders all form fields', () => {
renderModuleForm()
expect(screen.getByTestId('text-input-module-name')).toBeInTheDocument()
expect(screen.getByTestId('textarea-module-description')).toBeInTheDocument()
expect(screen.getByTestId('date-input-module-start-date')).toBeInTheDocument()
expect(screen.getByTestId('date-input-module-end-date')).toBeInTheDocument()
expect(screen.getByTestId('select')).toBeInTheDocument()
})
it('renders optional fields (domains, tags, labels)', () => {
renderModuleForm()
expect(screen.getByTestId('text-input-module-domains')).toBeInTheDocument()
expect(screen.getByTestId('text-input-module-tags')).toBeInTheDocument()
expect(screen.getByTestId('text-input-module-labels')).toBeInTheDocument()
})
it('renders mentor logins field only when isEdit is true (line 312)', () => {
renderModuleForm({ isEdit: false })
expect(screen.queryByTestId('text-input-module-mentor-logins')).not.toBeInTheDocument()
renderModuleForm({ isEdit: true })
expect(screen.getByTestId('text-input-module-mentor-logins')).toBeInTheDocument()
})
})
describe('Input Handling', () => {
it('updates name field', () => {
renderModuleForm()
const nameInput = screen.getByTestId('input-module-name')
fireEvent.change(nameInput, { target: { value: 'New Module Name' } })
expect(mockSetFormData).toHaveBeenCalled()
})
it('updates description field', () => {
renderModuleForm()
const descInput = screen.getByTestId('textarea-input-module-description')
fireEvent.change(descInput, { target: { value: 'New description' } })
expect(mockSetFormData).toHaveBeenCalled()
})
it('updates domains field (line 288 - handleInputChange for domains)', () => {
renderModuleForm()
const domainsInput = screen.getByTestId('input-module-domains')
fireEvent.change(domainsInput, { target: { value: 'AI, ML' } })
expect(mockSetFormData).toHaveBeenCalled()
})
it('updates tags field', () => {
renderModuleForm()
const tagsInput = screen.getByTestId('input-module-tags')
fireEvent.change(tagsInput, { target: { value: 'react, javascript' } })
expect(mockSetFormData).toHaveBeenCalled()
})
it('updates labels field (line 288)', () => {
renderModuleForm()
const labelsInput = screen.getByTestId('input-module-labels')
fireEvent.change(labelsInput, { target: { value: 'bug, enhancement' } })
expect(mockSetFormData).toHaveBeenCalled()
})
it('updates mentor logins field when in edit mode (line 312)', () => {
renderModuleForm({ isEdit: true })
const mentorInput = screen.getByTestId('input-module-mentor-logins')
fireEvent.change(mentorInput, { target: { value: 'johndoe, Kateryna' } })
expect(mockSetFormData).toHaveBeenCalled()
})
it('updates start date field', () => {
renderModuleForm()
const startDateContainer = screen.getByTestId('date-input-module-start-date')
const startDateInput = startDateContainer.querySelector('input')
expect(startDateInput).toBeTruthy()
if (startDateInput) {
fireEvent.change(startDateInput, { target: { value: '2024-01-01' } })
}
expect(mockSetFormData).toHaveBeenCalled()
})
it('updates end date field', () => {
renderModuleForm()
const endDateContainer = screen.getByTestId('date-input-module-end-date')
const endDateInput = endDateContainer.querySelector('input')
expect(endDateInput).toBeTruthy()
if (endDateInput) {
fireEvent.change(endDateInput, { target: { value: '2024-12-31' } })
}
expect(mockSetFormData).toHaveBeenCalled()
})
it('updates project field when ProjectSelector changes', async () => {
renderModuleForm()
const input = screen.getByTestId('autocomplete-input')
await act(async () => {
fireEvent.change(input, { target: { value: 'Test' } })
jest.advanceTimersByTime(350)
})
await waitFor(() => expect(mockQuery).toHaveBeenCalled())
const items = await screen.findAllByTestId('autocomplete-item')
await act(async () => {
fireEvent.click(items[0])
})
expect(mockSetFormData).toHaveBeenCalled()
})
it('updates project field when ProjectSelector is cleared', async () => {
const initialFormData = {
...defaultFormData,
projectId: 'proj-1',
projectName: 'Existing Project',
}
renderModuleForm({ formData: initialFormData })
const clearButton = screen.getByTestId('autocomplete-clear')
await act(async () => {
fireEvent.click(clearButton)
})
expect(mockSetFormData).toHaveBeenCalled()
const setterFn = mockSetFormData.mock.calls[mockSetFormData.mock.calls.length - 1][0]
const result = setterFn(initialFormData)
expect(result).toEqual(
expect.objectContaining({
projectId: '',
projectName: '',
})
)
})
})
describe('Experience Level Select - handleSelectChange (lines 74-84)', () => {
it('handles selection via Set (line 74-75)', () => {
renderModuleForm()
const setButton = screen.getByTestId('select-set')
fireEvent.click(setButton)
expect(mockSetFormData).toHaveBeenCalled()
})
it('handles "all" key selection (lines 76-77)', () => {
renderModuleForm()
const allButton = screen.getByTestId('select-all')
fireEvent.click(allButton)
// When 'all' is selected, an empty set is created and no value is set
// So setFormData should NOT be called in this case (line 82-84 checks if value exists)
expect(mockSetFormData).not.toHaveBeenCalled()
})
it('handles single key selection (lines 78-80)', () => {
renderModuleForm()
const singleButton = screen.getByTestId('select-single')
fireEvent.click(singleButton)
// Verify setFormData was called with a function (setter pattern)
expect(mockSetFormData).toHaveBeenCalled()
const setterFn = mockSetFormData.mock.calls[0][0]
expect(typeof setterFn).toBe('function')
// Call the setter function with previous state and verify it returns correct data
const result = setterFn(defaultFormData)
expect(result).toEqual(
expect.objectContaining({
experienceLevel: 'INTERMEDIATE',
})
)
})
})
describe('Form Submission - handleSubmit (lines 124-161)', () => {
it('prevents default form submission', () => {
renderModuleForm()
const form = document.querySelector('form')
expect(form).toBeInTheDocument()
const submitEvent = new Event('submit', { bubbles: true, cancelable: true })
jest.spyOn(submitEvent, 'preventDefault')
act(() => {
form!.dispatchEvent(submitEvent)
})
expect(submitEvent.preventDefault).toHaveBeenCalled()
})
it('does not call onSubmit when validation fails (line 157)', () => {
renderModuleForm() // Empty form data should fail validation
const form = document.querySelector('form')
if (form) {
fireEvent.submit(form)
}
// onSubmit should NOT be called because validation fails
expect(mockOnSubmit).not.toHaveBeenCalled()
})
it('calls onSubmit when all fields are valid', async () => {
const validFormData = {
...defaultFormData,
name: 'Valid Module Name',
description: 'A valid description that is long enough',
startedAt: '2024-01-01',
endedAt: '2024-12-31',
projectId: 'project-123',
projectName: 'My Project',
experienceLevel: 'BEGINNER',
}
renderModuleForm({ formData: validFormData })
const form = document.querySelector('form')
await act(async () => {
if (form) {
fireEvent.submit(form)
}
})
await waitFor(() => {
expect(mockOnSubmit).toHaveBeenCalled()
})
})
it('sets all fields as touched on submit', () => {
renderModuleForm()
const form = document.querySelector('form')
expect(form).toBeInTheDocument()
// Form should exist at this point based on above assertion
const formElement = form as HTMLFormElement
fireEvent.submit(formElement)
})
})
describe('Custom Submit Text', () => {
it('uses default submit text "Save"', () => {
renderModuleForm()
expect(screen.getByTestId('submit-button')).toHaveTextContent('Save')
})
it('uses custom submit text when provided', () => {
renderModuleForm({ submitText: 'Create Module' })
expect(screen.getByTestId('submit-button')).toHaveTextContent('Create Module')
})
})
describe('Loading State', () => {
it('disables submit button when loading', () => {
renderModuleForm({ loading: true })
expect(screen.getByTestId('submit-button')).toBeDisabled()
})
it('enables submit button when not loading', () => {
renderModuleForm({ loading: false })
expect(screen.getByTestId('submit-button')).not.toBeDisabled()
})
})
describe('Mutation Error Display (validationErrors prop)', () => {
const validFormData = {
...defaultFormData,
name: 'Test Module',
description: 'A valid description that is long enough',
startedAt: '2024-01-01',
endedAt: '2024-12-31',
projectId: 'project-123',
projectName: 'My Project',
experienceLevel: 'BEGINNER',
}
it('displays mutation error for name field after submission', () => {
const { rerender } = render(
<ModuleForm
formData={validFormData}
setFormData={mockSetFormData}
onSubmit={mockOnSubmit}
loading={false}
title="Create Module"
/>
)
// Submit first to mark fields as touched
const form = document.querySelector('form')
fireEvent.submit(form!)
// Rerender with mutation errors (simulates page catching backend error)
rerender(
<ModuleForm
formData={validFormData}
setFormData={mockSetFormData}
onSubmit={mockOnSubmit}
loading={false}
title="Create Module"
validationErrors={{
name: 'This module name already exists in this program.',
}}
/>
)
expect(screen.getByTestId('module-name-error')).toHaveTextContent(
'This module name already exists in this program.'
)
})
it('does not display mutation error when validationErrors is empty', () => {
renderModuleForm({
formData: validFormData,
validationErrors: {},
})
expect(screen.queryByTestId('module-name-error')).not.toBeInTheDocument()
})
it('allows resubmission even when validationErrors.name is set', async () => {
const { rerender } = render(
<ModuleForm
formData={validFormData}
setFormData={mockSetFormData}
onSubmit={mockOnSubmit}
loading={false}
title="Create Module"
/>
)
// First submit to mark fields as touched
const form = document.querySelector('form')
fireEvent.submit(form!)
expect(mockOnSubmit).toHaveBeenCalledTimes(1)
mockOnSubmit.mockClear()
// Rerender with mutation errors
rerender(
<ModuleForm
formData={validFormData}
setFormData={mockSetFormData}
onSubmit={mockOnSubmit}
loading={false}
title="Create Module"
validationErrors={{
name: 'This module name already exists in this program.',
}}
/>
)
// Second submit should still call onSubmit so parent can clear errors and retry
fireEvent.submit(form!)
await waitFor(() => {
expect(mockOnSubmit).toHaveBeenCalledTimes(1)
})
})
it('allows submission when validationErrors has no name error', async () => {
renderModuleForm({
formData: validFormData,
validationErrors: {},
})
const form = document.querySelector('form')
fireEvent.submit(form!)
await waitFor(() => {
expect(mockOnSubmit).toHaveBeenCalled()
})
})
it('allows submission when validationErrors is undefined', async () => {
renderModuleForm({
formData: validFormData,
})
const form = document.querySelector('form')
fireEvent.submit(form!)
await waitFor(() => {
expect(mockOnSubmit).toHaveBeenCalled()
})
})
})
})
describe('ProjectSelector', () => {
const mockOnProjectChange = jest.fn()
beforeEach(() => {
jest.clearAllMocks()
jest.useFakeTimers()
mockQuery.mockResolvedValue({
data: {
searchProjects: [
{ id: 'project-1', name: 'Test Project 1' },
{ id: 'project-2', name: 'Test Project 2' },
],
},
})
})
afterEach(() => {
jest.useRealTimers()
})
const renderProjectSelector = (props = {}) => {
const defaultProps = {
value: '',
defaultName: '',
onProjectChange: mockOnProjectChange,
...props,
}
return render(<ProjectSelector {...defaultProps} />)
}
describe('Basic Rendering', () => {
it('renders autocomplete component', () => {
renderProjectSelector()
expect(screen.getByTestId('autocomplete')).toBeInTheDocument()
})
it('renders with default name', () => {
renderProjectSelector({ defaultName: 'Initial Project' })
const input = screen.getByTestId('autocomplete-input')
expect(input).toHaveValue('Initial Project')
})
})
describe('Input Handling', () => {
it('updates input value on change', async () => {
renderProjectSelector()
const input = screen.getByTestId('autocomplete-input')
await act(async () => {
fireEvent.change(input, { target: { value: 'New Query' } })
})
expect(mockOnProjectChange).toHaveBeenCalledWith(null, 'New Query')
})
it('triggers search after debounce for queries >= 2 chars', async () => {
renderProjectSelector()
const input = screen.getByTestId('autocomplete-input')
await act(async () => {
fireEvent.change(input, { target: { value: 'Test' } })
jest.advanceTimersByTime(350)
})
await waitFor(() => {
expect(mockQuery).toHaveBeenCalled()
})
})
it('does not trigger search for queries < 2 chars', async () => {
renderProjectSelector()
const input = screen.getByTestId('autocomplete-input')
await act(async () => {
fireEvent.change(input, { target: { value: 'T' } })
jest.advanceTimersByTime(350)
})
// Query should not be called for single character
expect(mockQuery).not.toHaveBeenCalled()
})
})
describe('Selection Handling', () => {
it('selects a project when item is clicked', async () => {
mockQuery.mockResolvedValue({
data: {
searchProjects: [{ id: 'project-1', name: 'Test Project 1' }],
},
})
renderProjectSelector()
const input = screen.getByTestId('autocomplete-input')
await act(async () => {
fireEvent.change(input, { target: { value: 'Test' } })
jest.advanceTimersByTime(350)
})
await waitFor(() => expect(mockQuery).toHaveBeenCalled())
const items = await screen.findAllByTestId('autocomplete-item')
await act(async () => {
fireEvent.click(items[0])
})
expect(mockOnProjectChange).toHaveBeenCalledWith('project-1', 'Test Project 1')
})
it('clears selection when clear button is clicked', async () => {
renderProjectSelector({ value: 'project-1', defaultName: 'Existing Project' })
const clearButton = screen.getByTestId('autocomplete-clear')
await act(async () => {
fireEvent.click(clearButton)
})
expect(mockOnProjectChange).toHaveBeenCalledWith(null, '')
})
})
describe('useEffect - Value Sync', () => {
it('syncs inputValue when defaultName changes', () => {
const { rerender } = renderProjectSelector({ value: 'proj-1', defaultName: 'Project 1' })
rerender(
<ProjectSelector
value="proj-1"
defaultName="Updated Project Name"
onProjectChange={mockOnProjectChange}
/>
)
const input = screen.getByTestId('autocomplete-input')
expect(input).toHaveValue('Updated Project Name')
})
it('clears inputValue when value and defaultName become empty', () => {
const { rerender } = renderProjectSelector({ value: 'proj-1', defaultName: 'Project 1' })
rerender(<ProjectSelector value="" defaultName="" onProjectChange={mockOnProjectChange} />)
const input = screen.getByTestId('autocomplete-input')
expect(input).toHaveValue('')
})
})
describe('Error Handling - fetchSuggestions catch block (lines 380-385)', () => {
it('handles API errors gracefully', async () => {
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
mockQuery.mockRejectedValue(new Error('Network error'))
renderProjectSelector()
const input = screen.getByTestId('autocomplete-input')
await act(async () => {
fireEvent.change(input, { target: { value: 'Test Query' } })
jest.advanceTimersByTime(350)
})
await waitFor(() => {
expect(consoleErrorSpy).toHaveBeenCalledWith(
'Error fetching project suggestions:',
'Network error',
expect.any(Error)
)
})
consoleErrorSpy.mockRestore()
})
it('handles non-Error exceptions', async () => {
const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
mockQuery.mockRejectedValue('String error')
renderProjectSelector()
const input = screen.getByTestId('autocomplete-input')
await act(async () => {
fireEvent.change(input, { target: { value: 'Test Query' } })
jest.advanceTimersByTime(350)
})
await waitFor(() => {
expect(consoleErrorSpy).toHaveBeenCalledWith(
'Error fetching project suggestions:',
'String error',
'String error'
)
})
consoleErrorSpy.mockRestore()
})
it('handles missing searchProjects in response', async () => {
mockQuery.mockResolvedValue({ data: {} })
renderProjectSelector()
const input = screen.getByTestId('autocomplete-input')
await act(async () => {
fireEvent.change(input, { target: { value: 'Test' } })
jest.advanceTimersByTime(350)
})
await waitFor(() => {
expect(mockQuery).toHaveBeenCalled()
})
const items = screen.queryAllByTestId('autocomplete-item')
expect(items).toHaveLength(0)
})
})
describe('Validation Display', () => {
it('shows error message when isInvalid and not typing', () => {
renderProjectSelector({
value: '',
defaultName: '',
isInvalid: true,
errorMessage: 'Project is required',
})
expect(screen.getByTestId('autocomplete-error')).toHaveTextContent('Project is required')
})
it('hides error message when user is typing', () => {
renderProjectSelector({
value: '',
defaultName: 'Typing...',
isInvalid: true,
errorMessage: 'Project is required',
})
// When typing (inputValue has text but no value selected), error should be hidden
expect(screen.queryByTestId('autocomplete-error')).not.toBeInTheDocument()
})
})
describe('Project Filtering', () => {
it('filters out currently selected project from suggestions', async () => {
mockQuery.mockResolvedValue({
data: {
searchProjects: [
{ id: 'project-1', name: 'Test Project 1' },
{ id: 'project-2', name: 'Test Project 2' },
],
},
})
renderProjectSelector({ value: 'project-1', defaultName: 'Test Project 1' })
const input = screen.getByTestId('autocomplete-input')
await act(async () => {
fireEvent.change(input, { target: { value: 'Test' } })
jest.advanceTimersByTime(350)
})
await waitFor(() => {
expect(mockQuery).toHaveBeenCalled()
})
// Verify filtering: only project-2 should be in the rendered results
const autocompleteItems = screen.getAllByTestId('autocomplete-item')
expect(autocompleteItems).toHaveLength(1)
expect(autocompleteItems[0]).toHaveAttribute('data-text-value', 'Test Project 2')
// Explicitly verify project-1 is not rendered
const project1Item = autocompleteItems.find(
(item) => item.dataset.textValue === 'Test Project 1'
)
expect(project1Item).toBeUndefined()
})
})
})