-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
index.js
2430 lines (1966 loc) · 64.4 KB
/
index.js
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* External dependencies
*/
import { render, unmountComponentAtNode } from 'react-dom';
import { act, Simulate } from 'react-dom/test-utils';
import { queryByText, queryByRole } from '@testing-library/react';
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
import { UP, DOWN, ENTER } from '@wordpress/keycodes';
/**
* WordPress dependencies
*/
import { useSelect } from '@wordpress/data';
/**
* Internal dependencies
*/
import LinkControl from '../';
import {
fauxEntitySuggestions,
fetchFauxEntitySuggestions,
uniqueId,
} from './fixtures';
// Mock debounce() so that it runs instantly.
jest.mock( 'lodash', () => ( {
...jest.requireActual( 'lodash' ),
debounce: ( fn ) => {
fn.cancel = jest.fn();
return fn;
},
} ) );
const mockFetchSearchSuggestions = jest.fn();
/**
* The call to the real method `fetchRichUrlData` is wrapped in a promise in order to make it cancellable.
* Therefore if we pass any value as the mock of `fetchRichUrlData` then ALL of the tests will require
* addition code to handle the async nature of `fetchRichUrlData`. This is unecessary. Instead we default
* to an undefined value which will ensure that the code under test does not call `fetchRichUrlData`. Only
* when we are testing the "rich previews" to we update this value with a true mock.
*/
let mockFetchRichUrlData;
jest.mock( '@wordpress/data/src/components/use-select', () => {
// This allows us to tweak the returned value on each test.
const mock = jest.fn();
return mock;
} );
useSelect.mockImplementation( () => ( {
fetchSearchSuggestions: mockFetchSearchSuggestions,
fetchRichUrlData: mockFetchRichUrlData,
} ) );
jest.mock( '@wordpress/data/src/components/use-dispatch', () => ( {
useDispatch: () => ( { saveEntityRecords: jest.fn() } ),
} ) );
jest.useRealTimers();
/**
* Wait for next tick of event loop. This is required
* because the `fetchSearchSuggestions` Promise will
* resolve on the next tick of the event loop (this is
* inline with the Promise spec). As a result we need to
* wait on this loop to "tick" before we can expect the UI
* to have updated.
*/
function eventLoopTick() {
return new Promise( ( resolve ) => setImmediate( resolve ) );
}
let container = null;
beforeEach( () => {
// Setup a DOM element as a render target.
container = document.createElement( 'div' );
document.body.appendChild( container );
mockFetchSearchSuggestions.mockImplementation( fetchFauxEntitySuggestions );
} );
afterEach( () => {
// Cleanup on exiting.
unmountComponentAtNode( container );
container.remove();
container = null;
mockFetchSearchSuggestions.mockReset();
mockFetchRichUrlData?.mockReset(); // Conditionally reset as it may NOT be a mock.
} );
function getURLInput() {
return container.querySelector( 'input[aria-label="URL"]' );
}
function getSearchResults() {
const input = getURLInput();
// The input has `aria-owns` to indicate that it owns (and is related to)
// the search results with `role="listbox"`.
const relatedSelector = input.getAttribute( 'aria-owns' );
// Select by relationship as well as role.
return container.querySelectorAll(
`#${ relatedSelector }[role="listbox"] [role="option"]`
);
}
function getCurrentLink() {
return container.querySelector(
'.block-editor-link-control__search-item.is-current'
);
}
describe( 'Basic rendering', () => {
it( 'should render', () => {
act( () => {
render( <LinkControl />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
expect( searchInput ).not.toBeNull();
} );
it( 'should not render protocol in links', async () => {
mockFetchSearchSuggestions.mockImplementation( () =>
Promise.resolve( [
{
id: uniqueId(),
title: 'Hello Page',
type: 'Page',
info: '2 days ago',
url: `http://example.com/?p=${ uniqueId() }`,
},
{
id: uniqueId(),
title: 'Hello Post',
type: 'Post',
info: '19 days ago',
url: `https://example.com/${ uniqueId() }`,
},
] )
);
const searchTerm = 'Hello';
act( () => {
render( <LinkControl />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, { target: { value: searchTerm } } );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
// Find all elements with link
// Filter out the element with the text 'ENTER' because it doesn't contain link.
const linkElements = Array.from(
container.querySelectorAll(
'.block-editor-link-control__search-item-info'
)
).filter( ( elem ) => ! elem.innerHTML.includes( 'ENTER' ) );
linkElements.forEach( ( elem ) => {
expect( elem.innerHTML ).not.toContain( '://' );
} );
} );
describe( 'forceIsEditingLink', () => {
const isEditing = () => !! getURLInput();
it( 'undefined', () => {
act( () => {
render(
<LinkControl value={ { url: 'https://example.com' } } />,
container
);
} );
expect( isEditing() ).toBe( false );
} );
it( 'true', () => {
act( () => {
render(
<LinkControl
value={ { url: 'https://example.com' } }
forceIsEditingLink
/>,
container
);
} );
expect( isEditing() ).toBe( true );
} );
it( 'false', () => {
act( () => {
render(
<LinkControl value={ { url: 'https://example.com' } } />,
container
);
} );
// Click the "Edit" button to trigger into the editing mode.
const editButton = queryByRole( container, 'button', {
name: 'Edit',
} );
act( () => {
Simulate.click( editButton );
} );
expect( isEditing() ).toBe( true );
// If passed `forceIsEditingLink` of `false` while editing, should
// forcefully reset to the preview state.
act( () => {
render(
<LinkControl
value={ { url: 'https://example.com' } }
forceIsEditingLink={ false }
/>,
container
);
} );
expect( isEditing() ).toBe( false );
} );
it( 'should display human friendly error message if value URL prop is empty when component is forced into no-editing (preview) mode', async () => {
// Why do we need this test?
// Occasionally `forceIsEditingLink` is set explictly to `false` which causes the Link UI to render
// it's preview even if the `value` has no URL.
// for an example of this see the usage in the following file whereby forceIsEditingLink is used to start/stop editing mode:
// https://github.com/WordPress/gutenberg/blob/fa5728771df7cdc86369f7157d6aa763649937a7/packages/format-library/src/link/inline.js#L151.
// see also: https://github.com/WordPress/gutenberg/issues/17972.
const valueWithEmptyURL = {
url: '',
id: 123,
type: 'post',
};
act( () => {
render(
<LinkControl
value={ valueWithEmptyURL }
forceIsEditingLink={ false }
/>,
container
);
} );
const linkPreview = queryByRole( container, 'generic', {
name: 'Currently selected',
} );
const isPreviewError = linkPreview.classList.contains( 'is-error' );
expect( isPreviewError ).toBe( true );
expect( queryByText( linkPreview, 'Link is empty' ) ).toBeTruthy();
} );
} );
describe( 'Unlinking', () => {
it( 'should not show "Unlink" button if no onRemove handler is provided', () => {
act( () => {
render(
<LinkControl value={ { url: 'https://example.com' } } />,
container
);
} );
const unLinkButton = queryByRole( container, 'button', {
name: 'Unlink',
} );
expect( unLinkButton ).toBeNull();
expect( unLinkButton ).not.toBeInTheDocument();
} );
it( 'should show "Unlink" button if a onRemove handler is provided', () => {
const mockOnRemove = jest.fn();
act( () => {
render(
<LinkControl
value={ { url: 'https://example.com' } }
onRemove={ mockOnRemove }
/>,
container
);
} );
const unLinkButton = queryByRole( container, 'button', {
name: 'Unlink',
} );
expect( unLinkButton ).toBeTruthy();
expect( unLinkButton ).toBeInTheDocument();
act( () => {
Simulate.click( unLinkButton );
} );
expect( mockOnRemove ).toHaveBeenCalled();
} );
} );
} );
describe( 'Searching for a link', () => {
it( 'should display loading UI when input is valid but search results have yet to be returned', async () => {
const searchTerm = 'Hello';
let resolver;
const fauxRequest = () =>
new Promise( ( resolve ) => {
resolver = resolve;
} );
mockFetchSearchSuggestions.mockImplementation( fauxRequest );
act( () => {
render( <LinkControl />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, { target: { value: searchTerm } } );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
const searchResultElements = getSearchResults();
let loadingUI = container.querySelector( '.components-spinner' );
expect( searchResultElements ).toHaveLength( 0 );
expect( loadingUI ).not.toBeNull();
act( () => {
resolver( fauxEntitySuggestions );
} );
await eventLoopTick();
loadingUI = container.querySelector( '.components-spinner' );
expect( loadingUI ).toBeNull();
} );
it( 'should display only search suggestions when current input value is not URL-like', async () => {
const searchTerm = 'Hello world';
const firstFauxSuggestion = fauxEntitySuggestions[ 0 ];
act( () => {
render( <LinkControl />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, { target: { value: searchTerm } } );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
// TODO: select these by aria relationship to autocomplete rather than arbitrary selector.
const searchResultElements = getSearchResults();
const firstSearchResultItemHTML = searchResultElements[ 0 ].innerHTML;
const lastSearchResultItemHTML =
searchResultElements[ searchResultElements.length - 1 ].innerHTML;
expect( searchResultElements ).toHaveLength(
fauxEntitySuggestions.length
);
expect( searchInput.getAttribute( 'aria-expanded' ) ).toBe( 'true' );
// Sanity check that a search suggestion shows up corresponding to the data.
expect( firstSearchResultItemHTML ).toEqual(
expect.stringContaining( firstFauxSuggestion.title )
);
expect( firstSearchResultItemHTML ).toEqual(
expect.stringContaining( firstFauxSuggestion.type )
);
// The fallback URL suggestion should not be shown when input is not URL-like.
expect( lastSearchResultItemHTML ).not.toEqual(
expect.stringContaining( 'URL' )
);
} );
it( 'should trim search term', async () => {
const searchTerm = ' Hello ';
act( () => {
render( <LinkControl />, container );
} );
// Search Input UI.
const searchInput = container.querySelector(
'input[aria-label="URL"]'
);
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, { target: { value: searchTerm } } );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
const searchResultTextHighlightElements = Array.from(
container.querySelectorAll(
'[role="listbox"] button[role="option"] mark'
)
);
const invalidResults = searchResultTextHighlightElements.find(
( mark ) => mark.innerHTML !== 'Hello'
);
// Grab the first argument that was passed to the fetchSuggestions
// handler (which is mocked out).
const mockFetchSuggestionsFirstArg =
mockFetchSearchSuggestions.mock.calls[ 0 ][ 0 ];
// Given we're mocking out the results we should always have 4 mark elements.
expect( searchResultTextHighlightElements ).toHaveLength( 4 );
// Make sure there are no `mark` elements which contain anything other
// than the trimmed search term (ie: no whitespace).
expect( invalidResults ).toBeFalsy();
// Implementation detail test to ensure that the fetch handler is called
// with the trimmed search value. We do this because we are mocking out
// the fetch handler in our test so we need to assert it would be called
// correctly in a real world scenario.
expect( mockFetchSuggestionsFirstArg ).toEqual( 'Hello' );
} );
it( 'should not call search handler when showSuggestions is false', async () => {
act( () => {
render( <LinkControl showSuggestions={ false } />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, {
target: { value: 'anything' },
} );
} );
const searchResultElements = getSearchResults();
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
// TODO: select these by aria relationship to autocomplete rather than arbitrary selector.
expect( searchResultElements ).toHaveLength( 0 );
expect( mockFetchSearchSuggestions ).not.toHaveBeenCalled();
} );
it.each( [
[ 'couldbeurlorentitysearchterm' ],
[ 'ThisCouldAlsoBeAValidURL' ],
] )(
'should display a URL suggestion as a default fallback for the search term "%s" which could potentially be a valid url.',
async ( searchTerm ) => {
act( () => {
render( <LinkControl />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, {
target: { value: searchTerm },
} );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
// TODO: select these by aria relationship to autocomplete rather than arbitrary selector.
const searchResultElements = getSearchResults();
const lastSearchResultItemHTML =
searchResultElements[ searchResultElements.length - 1 ]
.innerHTML;
const additionalDefaultFallbackURLSuggestionLength = 1;
// We should see a search result for each of the expect search suggestions
// plus 1 additional one for the fallback URL suggestion.
expect( searchResultElements ).toHaveLength(
fauxEntitySuggestions.length +
additionalDefaultFallbackURLSuggestionLength
);
// The last item should be a URL search suggestion.
expect( lastSearchResultItemHTML ).toEqual(
expect.stringContaining( searchTerm )
);
expect( lastSearchResultItemHTML ).toEqual(
expect.stringContaining( 'URL' )
);
expect( lastSearchResultItemHTML ).toEqual(
expect.stringContaining( 'Press ENTER to add this link' )
);
}
);
it( 'should not display a URL suggestion as a default fallback when noURLSuggestion is passed.', async () => {
act( () => {
render( <LinkControl noURLSuggestion />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, {
target: { value: 'couldbeurlorentitysearchterm' },
} );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
// TODO: select these by aria relationship to autocomplete rather than arbitrary selector.
const searchResultElements = getSearchResults();
// We should see a search result for each of the expect search suggestions and nothing else.
expect( searchResultElements ).toHaveLength(
fauxEntitySuggestions.length
);
} );
} );
describe( 'Manual link entry', () => {
it.each( [
[ 'https://make.wordpress.org' ], // Explicit https.
[ 'http://make.wordpress.org' ], // Explicit http.
[ 'www.wordpress.org' ], // Usage of "www".
] )(
'should display a single suggestion result when the current input value is URL-like (eg: %s)',
async ( searchTerm ) => {
act( () => {
render( <LinkControl />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, {
target: { value: searchTerm },
} );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
const searchResultElements = getSearchResults();
const firstSearchResultItemHTML =
searchResultElements[ 0 ].innerHTML;
const expectedResultsLength = 1;
expect( searchResultElements ).toHaveLength(
expectedResultsLength
);
expect( firstSearchResultItemHTML ).toEqual(
expect.stringContaining( searchTerm )
);
expect( firstSearchResultItemHTML ).toEqual(
expect.stringContaining( 'URL' )
);
expect( firstSearchResultItemHTML ).toEqual(
expect.stringContaining( 'Press ENTER to add this link' )
);
}
);
describe( 'Handling of empty values', () => {
const testTable = [
[ 'containing only spaces', ' ' ],
[ 'containing only tabs', ' ' ],
[ 'from strings with no length', '' ],
];
it.each( testTable )(
'should not allow creation of links %s when using the keyboard',
async ( _desc, searchString ) => {
act( () => {
render( <LinkControl />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
let submitButton = queryByRole( container, 'button', {
name: 'Submit',
} );
expect( submitButton.disabled ).toBeTruthy();
expect( submitButton ).not.toBeNull();
expect( submitButton ).toBeInTheDocument();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, {
target: { value: searchString },
} );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
// Attempt to submit the empty search value in the input.
act( () => {
Simulate.keyDown( searchInput, { keyCode: ENTER } );
} );
submitButton = queryByRole( container, 'button', {
name: 'Submit',
} );
// Verify the UI hasn't allowed submission.
expect( searchInput ).toBeInTheDocument();
expect( submitButton.disabled ).toBeTruthy();
expect( submitButton ).not.toBeNull();
expect( submitButton ).toBeInTheDocument();
}
);
it.each( testTable )(
'should not allow creation of links %s via the UI "submit" button',
async ( _desc, searchString ) => {
act( () => {
render( <LinkControl />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
let submitButton = queryByRole( container, 'button', {
name: 'Submit',
} );
expect( submitButton.disabled ).toBeTruthy();
expect( submitButton ).not.toBeNull();
expect( submitButton ).toBeInTheDocument();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, {
target: { value: searchString },
} );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
// Attempt to submit the empty search value in the input.
act( () => {
Simulate.click( submitButton );
} );
submitButton = queryByRole( container, 'button', {
name: 'Submit',
} );
// Verify the UI hasn't allowed submission.
expect( searchInput ).toBeInTheDocument();
expect( submitButton.disabled ).toBeTruthy();
expect( submitButton ).not.toBeNull();
expect( submitButton ).toBeInTheDocument();
}
);
} );
describe( 'Alternative link protocols and formats', () => {
it.each( [
[ 'mailto:example123456@wordpress.org', 'mailto' ],
[ 'tel:example123456@wordpress.org', 'tel' ],
[ '#internal-anchor', 'internal' ],
] )(
'should recognise "%s" as a %s link and handle as manual entry by displaying a single suggestion',
async ( searchTerm, searchType ) => {
act( () => {
render( <LinkControl />, container );
} );
// Search Input UI.
const searchInput = getURLInput();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, {
target: { value: searchTerm },
} );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
const searchResultElements = getSearchResults();
const firstSearchResultItemHTML =
searchResultElements[ 0 ].innerHTML;
const expectedResultsLength = 1;
expect( searchResultElements ).toHaveLength(
expectedResultsLength
);
expect( firstSearchResultItemHTML ).toEqual(
expect.stringContaining( searchTerm )
);
expect( firstSearchResultItemHTML ).toEqual(
expect.stringContaining( searchType )
);
expect( firstSearchResultItemHTML ).toEqual(
expect.stringContaining( 'Press ENTER to add this link' )
);
}
);
} );
} );
describe( 'Default search suggestions', () => {
it( 'should display a list of initial search suggestions when there is no search value or suggestions', async () => {
const expectedResultsLength = 3; // Set within `LinkControl`.
act( () => {
render( <LinkControl showInitialSuggestions />, container );
} );
await eventLoopTick();
// Search Input UI.
const searchInput = getURLInput();
const searchResultsWrapper =
container.querySelector( '[role="listbox"]' );
const initialSearchResultElements =
searchResultsWrapper.querySelectorAll( '[role="option"]' );
const searchResultsLabel = container.querySelector(
`#${ searchResultsWrapper.getAttribute( 'aria-labelledby' ) }`
);
// Verify input has no value has default suggestions should only show
// when this does not have a value.
expect( searchInput.value ).toBe( '' );
// Ensure only called once as a guard against potential infinite
// re-render loop within `componentDidUpdate` calling `updateSuggestions`
// which has calls to `setState` within it.
expect( mockFetchSearchSuggestions ).toHaveBeenCalledTimes( 1 );
// Verify the search results already display the initial suggestions.
expect( initialSearchResultElements ).toHaveLength(
expectedResultsLength
);
expect( searchResultsLabel.innerHTML ).toEqual( 'Recently updated' );
} );
it( 'should not display initial suggestions when input value is present', async () => {
// Render with an initial value an ensure that no initial suggestions
// are shown.
act( () => {
render(
<LinkControl
showInitialSuggestions
value={ fauxEntitySuggestions[ 0 ] }
/>,
container
);
} );
await eventLoopTick();
expect( mockFetchSearchSuggestions ).not.toHaveBeenCalled();
// Click the "Edit/Change" button and check initial suggestions are not
// shown.
const currentLinkUI = getCurrentLink();
const currentLinkBtn = currentLinkUI.querySelector( 'button' );
act( () => {
Simulate.click( currentLinkBtn );
} );
const searchInput = getURLInput();
searchInput.focus();
await eventLoopTick();
const searchResultElements = getSearchResults();
// Search input is set to the URL value.
expect( searchInput.value ).toEqual( fauxEntitySuggestions[ 0 ].url );
// It should match any url that's like ?p= and also include a URL option.
expect( searchResultElements ).toHaveLength( 5 );
expect( searchInput.getAttribute( 'aria-expanded' ) ).toBe( 'true' );
expect( mockFetchSearchSuggestions ).toHaveBeenCalledTimes( 1 );
} );
it( 'should display initial suggestions when input value is manually deleted', async () => {
const searchTerm = 'Hello world';
act( () => {
render( <LinkControl showInitialSuggestions />, container );
} );
let searchResultElements;
let searchInput;
// Search Input UI.
searchInput = getURLInput();
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, { target: { value: searchTerm } } );
} );
// fetchFauxEntitySuggestions resolves on next "tick" of event loop.
await eventLoopTick();
expect( searchInput.value ).toBe( searchTerm );
searchResultElements = getSearchResults();
// Delete the text.
act( () => {
Simulate.change( searchInput, { target: { value: '' } } );
} );
await eventLoopTick();
searchResultElements = getSearchResults();
searchInput = getURLInput();
// Check the input is empty now.
expect( searchInput.value ).toBe( '' );
const searchResultLabel = container.querySelector(
'.block-editor-link-control__search-results-label'
);
expect( searchResultLabel.innerHTML ).toBe( 'Recently updated' );
expect( searchResultElements ).toHaveLength( 3 );
} );
it( 'should not display initial suggestions when there are no recently updated pages/posts', async () => {
const noResults = [];
// Force API returning empty results for recently updated Pages.
mockFetchSearchSuggestions.mockImplementation( () =>
Promise.resolve( noResults )
);
act( () => {
render( <LinkControl showInitialSuggestions />, container );
} );
await eventLoopTick();
const searchInput = getURLInput();
const searchResultElements = getSearchResults();
const searchResultLabel = container.querySelector(
'.block-editor-link-control__search-results-label'
);
expect( searchResultLabel ).toBeFalsy();
expect( searchResultElements ).toHaveLength( 0 );
expect( searchInput.getAttribute( 'aria-expanded' ) ).toBe( 'false' );
} );
} );
describe( 'Creating Entities (eg: Posts, Pages)', () => {
const noResults = [];
beforeEach( () => {
// Force returning empty results for existing Pages. Doing this means that the only item
// shown should be "Create Page" suggestion because there will be no search suggestions
// and our input does not conform to a direct entry schema (eg: a URL).
mockFetchSearchSuggestions.mockImplementation( () =>
Promise.resolve( noResults )
);
} );
it.each( [
[ 'HelloWorld', 'without spaces' ],
[ 'Hello World', 'with spaces' ],
] )(
'should allow creating a link for a valid Entity title "%s" (%s)',
async ( entityNameText ) => {
let resolver;
let resolvedEntity;
const createSuggestion = ( title ) =>
new Promise( ( resolve ) => {
resolver = ( arg ) => {
resolve( arg );
};
resolvedEntity = {
title,
id: 123,
url: '/?p=123',
type: 'page',
};
} );
const LinkControlConsumer = () => {
const [ link, setLink ] = useState( null );
return (
<LinkControl
value={ link }
onChange={ ( suggestion ) => {
setLink( suggestion );
} }
createSuggestion={ createSuggestion }
/>
);
};
act( () => {
render( <LinkControlConsumer />, container );
} );
// Search Input UI.
const searchInput = container.querySelector(
'input[aria-label="URL"]'
);
// Simulate searching for a term.
act( () => {
Simulate.change( searchInput, {
target: { value: entityNameText },
} );
} );
await eventLoopTick();
// TODO: select these by aria relationship to autocomplete rather than arbitrary selector.
const searchResultElements = container.querySelectorAll(
'[role="listbox"] [role="option"]'
);
const createButton = Array.from( searchResultElements ).filter(
( result ) => result.innerHTML.includes( 'Create:' )
)[ 0 ];
expect( createButton ).not.toBeNull();
expect( createButton.innerHTML ).toEqual(
expect.stringContaining( entityNameText )
);
// No need to wait in this test because we control the Promise
// resolution manually via the `resolver` reference.
act( () => {
Simulate.click( createButton );
} );
await eventLoopTick();