-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathBrowserUrlBar.test.tsx
More file actions
635 lines (533 loc) · 19.3 KB
/
Copy pathBrowserUrlBar.test.tsx
File metadata and controls
635 lines (533 loc) · 19.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
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
import React, { createRef } from 'react';
import renderWithProvider from '../../../util/test/renderWithProvider';
import BrowserUrlBar from './BrowserUrlBar';
import { ConnectionType, BrowserUrlBarRef } from './BrowserUrlBar.types';
import { useMetrics } from '../../../components/hooks/useMetrics';
import { backgroundState } from '../../../util/test/initial-root-state';
import { selectAccountsLength } from '../../../selectors/accountTrackerController';
import {
selectNetworkConfigurations,
selectProviderConfig,
} from '../../../selectors/networkController';
import { fireEvent, act } from '@testing-library/react-native';
import { BrowserURLBarSelectorsIDs } from './BrowserURLBar.testIds';
import { AccountOverviewSelectorsIDs } from '../AccountRightButton/AccountOverview.testIds';
import Routes from '../../../constants/navigation/Routes';
const mockNavigate = jest.fn();
const navigation = {
params: {
url: 'https://metamask.github.io/test-dapp/',
},
};
jest.mock('@react-navigation/native', () => {
const actualNav = jest.requireActual('@react-navigation/native');
return {
...actualNav,
useNavigation: () => ({
navigate: mockNavigate,
}),
useRoute: jest.fn(() => ({ params: navigation.params })),
};
});
jest.mock('../../../components/hooks/useMetrics', () => ({
useMetrics: jest.fn(),
}));
const mockTrackEvent = jest.fn();
const mockCreateEventBuilder = jest.fn(() => ({
addProperties: jest.fn(() => ({
build: jest.fn(),
})),
}));
const mockInitialState = {
engine: {
backgroundState,
},
};
const mockUseSelector = jest.fn();
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: (callback: unknown) => mockUseSelector(callback),
}));
describe('BrowserUrlBar', () => {
const defaultProps = {
connectionType: ConnectionType.SECURE,
onSubmitEditing: jest.fn(),
onCancel: jest.fn(),
onFocus: jest.fn(),
onBlur: jest.fn(),
onChangeText: jest.fn(),
connectedAccounts: ['0x123'],
activeUrl: 'https://example.com',
setIsUrlBarFocused: jest.fn(),
isUrlBarFocused: true,
};
const propsWithoutUrlBarFocused = {
connectionType: ConnectionType.SECURE,
onSubmitEditing: jest.fn(),
onCancel: jest.fn(),
onFocus: jest.fn(),
onBlur: jest.fn(),
onChangeText: jest.fn(),
connectedAccounts: ['0x123'],
activeUrl: 'https://example.com',
setIsUrlBarFocused: jest.fn(),
isUrlBarFocused: false,
};
beforeEach(() => {
jest.clearAllMocks();
(useMetrics as jest.Mock).mockReturnValue({
trackEvent: mockTrackEvent,
createEventBuilder: mockCreateEventBuilder,
});
mockUseSelector.mockImplementation((selector) => {
if (selector === selectAccountsLength) return 1;
if (selector === selectNetworkConfigurations) return {};
if (selector === selectProviderConfig) return { chainId: '0x1' };
return null;
});
});
it('render matches snapshot when focused', () => {
const { toJSON } = renderWithProvider(<BrowserUrlBar {...defaultProps} />, {
state: mockInitialState,
});
expect(toJSON()).toMatchSnapshot();
});
it('render matches snapshot when not focused', () => {
const { toJSON } = renderWithProvider(
<BrowserUrlBar {...propsWithoutUrlBarFocused} />,
{
state: mockInitialState,
},
);
expect(toJSON()).toMatchSnapshot();
});
it('calls onChangeText when text input changes', () => {
const { getByTestId } = renderWithProvider(
<BrowserUrlBar {...defaultProps} />,
{
state: mockInitialState,
},
);
const urlInput = getByTestId(BrowserURLBarSelectorsIDs.URL_INPUT);
fireEvent.changeText(urlInput, 'test.com');
expect(defaultProps.onChangeText).toHaveBeenCalledWith('test.com');
});
it('trims whitespace and calls onSubmitEditing when text is submitted', () => {
const { getByTestId } = renderWithProvider(
<BrowserUrlBar {...defaultProps} />,
{
state: mockInitialState,
},
);
const urlInput = getByTestId(BrowserURLBarSelectorsIDs.URL_INPUT);
fireEvent(urlInput, 'submitEditing', {
nativeEvent: { text: ' test.com ' },
});
expect(defaultProps.onSubmitEditing).toHaveBeenCalledWith('test.com');
});
it('clears input and calls onChangeText when clear button is pressed', () => {
const { getByTestId } = renderWithProvider(
<BrowserUrlBar {...defaultProps} />,
{
state: mockInitialState,
},
);
const clearButton = getByTestId(BrowserURLBarSelectorsIDs.URL_CLEAR_ICON);
fireEvent.press(clearButton);
expect(defaultProps.onChangeText).toHaveBeenCalledWith('');
});
it('calls onCancel and sets focus state to false when cancel button is pressed', () => {
const { getByTestId } = renderWithProvider(
<BrowserUrlBar {...defaultProps} />,
{
state: mockInitialState,
},
);
const cancelButton = getByTestId(
BrowserURLBarSelectorsIDs.CANCEL_BUTTON_ON_BROWSER_ID,
);
fireEvent.press(cancelButton);
expect(defaultProps.onCancel).toHaveBeenCalled();
expect(defaultProps.setIsUrlBarFocused).toHaveBeenCalledWith(false);
});
it('tracks analytics events and navigates to account permissions when account button is pressed', () => {
const { getByTestId } = renderWithProvider(
<BrowserUrlBar {...propsWithoutUrlBarFocused} />,
{ state: mockInitialState },
);
const accountButton = getByTestId(
AccountOverviewSelectorsIDs.ACCOUNT_BUTTON,
);
fireEvent.press(accountButton);
expect(mockTrackEvent).toHaveBeenCalledTimes(2);
expect(mockNavigate).toHaveBeenCalledWith(Routes.MODAL.ROOT_MODAL_FLOW, {
screen: Routes.SHEET.ACCOUNT_PERMISSIONS,
params: {
hostInfo: {
metadata: {
origin: 'https://example.com',
},
},
},
});
});
it('updates focus state and calls focus/blur callbacks when input receives focus events', () => {
const { getByTestId } = renderWithProvider(
<BrowserUrlBar {...defaultProps} />,
{
state: mockInitialState,
},
);
const urlInput = getByTestId(BrowserURLBarSelectorsIDs.URL_INPUT);
fireEvent(urlInput, 'focus');
expect(defaultProps.setIsUrlBarFocused).toHaveBeenCalledWith(true);
expect(defaultProps.onFocus).toHaveBeenCalled();
fireEvent(urlInput, 'blur');
expect(defaultProps.setIsUrlBarFocused).toHaveBeenCalledWith(false);
expect(defaultProps.onBlur).toHaveBeenCalled();
});
it('renders UNSECURE connection icon when connection type is UNSECURE', () => {
const propsWithUnsecureConnection = {
...defaultProps,
connectionType: ConnectionType.UNSECURE,
isUrlBarFocused: false,
};
const { getByTestId } = renderWithProvider(
<BrowserUrlBar {...propsWithUnsecureConnection} />,
{ state: mockInitialState },
);
const urlInput = getByTestId(BrowserURLBarSelectorsIDs.URL_INPUT);
expect(urlInput).toBeDefined();
});
it('skips normal blur handling when shouldTriggerBlurCallbackRef is false', () => {
const onBlurMock = jest.fn();
const setIsUrlBarFocusedMock = jest.fn();
const props = {
...defaultProps,
onBlur: onBlurMock,
setIsUrlBarFocused: setIsUrlBarFocusedMock,
};
const { getByTestId } = renderWithProvider(<BrowserUrlBar {...props} />, {
state: mockInitialState,
});
const urlInput = getByTestId(BrowserURLBarSelectorsIDs.URL_INPUT);
const cancelButton = getByTestId(
BrowserURLBarSelectorsIDs.CANCEL_BUTTON_ON_BROWSER_ID,
);
// Clear previous calls
onBlurMock.mockClear();
setIsUrlBarFocusedMock.mockClear();
// Press cancel which sets shouldTriggerBlurCallbackRef to false before blurring
fireEvent.press(cancelButton);
// Now trigger blur event on the input
fireEvent(urlInput, 'blur');
// onBlur callback from props should have been called once from cancel
// but the blur event handler should have skipped the normal blur logic
// because shouldTriggerBlurCallbackRef was set to false
expect(onBlurMock).toHaveBeenCalledTimes(0);
});
it('triggers focus callback when URL text is pressed', () => {
const { getByText } = renderWithProvider(
<BrowserUrlBar {...propsWithoutUrlBarFocused} />,
{ state: mockInitialState },
);
const urlText = getByText('https://example.com');
// Press the URL text to trigger the focus callback
fireEvent.press(urlText);
// The component handles the press internally
expect(urlText).toBeDefined();
});
describe('useImperativeHandle methods', () => {
let urlBarRef: React.RefObject<BrowserUrlBarRef>;
beforeEach(() => {
// Arrange - Create ref for each test
urlBarRef = createRef<BrowserUrlBarRef>();
jest.clearAllMocks();
(useMetrics as jest.Mock).mockReturnValue({
trackEvent: mockTrackEvent,
createEventBuilder: mockCreateEventBuilder,
});
mockUseSelector.mockImplementation((selector) => {
if (selector === selectAccountsLength) return 1;
if (selector === selectNetworkConfigurations) return {};
if (selector === selectProviderConfig) return { chainId: '0x1' };
return null;
});
});
describe('hide method', () => {
it('calls onCancel prop when hide is invoked', () => {
// Arrange
const onCancelMock = jest.fn();
const props = { ...defaultProps, onCancel: onCancelMock };
renderWithProvider(<BrowserUrlBar {...props} ref={urlBarRef} />, {
state: mockInitialState,
});
// Act
act(() => {
urlBarRef.current?.hide();
});
// Assert
expect(onCancelMock).toHaveBeenCalledTimes(1);
});
it('sets URL bar focused state to false when hide is invoked', () => {
// Arrange
const setIsUrlBarFocusedMock = jest.fn();
const props = {
...defaultProps,
setIsUrlBarFocused: setIsUrlBarFocusedMock,
isUrlBarFocused: true,
};
renderWithProvider(<BrowserUrlBar {...props} ref={urlBarRef} />, {
state: mockInitialState,
});
// Act
act(() => {
urlBarRef.current?.hide();
});
// Assert
expect(setIsUrlBarFocusedMock).toHaveBeenCalledWith(false);
});
});
describe('focus method', () => {
it('exposes focus method through imperative handle', () => {
// Arrange
renderWithProvider(
<BrowserUrlBar {...defaultProps} ref={urlBarRef} />,
{ state: mockInitialState },
);
// Act & Assert - Should not throw errors and should be callable
expect(() => urlBarRef.current?.focus()).not.toThrow();
expect(typeof urlBarRef.current?.focus).toBe('function');
});
});
describe('blur method', () => {
it('exposes blur method through imperative handle', () => {
// Arrange
renderWithProvider(
<BrowserUrlBar {...defaultProps} ref={urlBarRef} />,
{ state: mockInitialState },
);
// Act & Assert - Should not throw errors and should be callable
expect(() => urlBarRef.current?.blur()).not.toThrow();
expect(typeof urlBarRef.current?.blur).toBe('function');
});
});
describe('setNativeProps method', () => {
it('delegates to underlying TextInput setNativeProps when called', () => {
// Arrange
renderWithProvider(
<BrowserUrlBar {...propsWithoutUrlBarFocused} ref={urlBarRef} />,
{ state: mockInitialState },
);
// Act & Assert - Should not throw errors when calling setNativeProps
expect(() => {
act(() => {
urlBarRef.current?.setNativeProps({ text: 'newsite.com' });
});
}).not.toThrow();
// Additional test: setNativeProps should be a function
expect(typeof urlBarRef.current?.setNativeProps).toBe('function');
});
it('exposes setNativeProps method through imperative handle', () => {
// Arrange
renderWithProvider(
<BrowserUrlBar {...defaultProps} ref={urlBarRef} />,
{ state: mockInitialState },
);
const testProps = { text: 'test.com', placeholder: 'test placeholder' };
// Act & Assert - Should not throw errors and should be callable
expect(() => {
act(() => {
urlBarRef.current?.setNativeProps(testProps);
});
}).not.toThrow();
expect(typeof urlBarRef.current?.setNativeProps).toBe('function');
});
it('handles non-string text values without throwing errors', () => {
// Arrange
renderWithProvider(
<BrowserUrlBar {...propsWithoutUrlBarFocused} ref={urlBarRef} />,
{ state: mockInitialState },
);
// Act & Assert - Should not throw errors when passing non-string text
expect(() => {
act(() => {
urlBarRef.current?.setNativeProps({ text: 123 as number });
});
}).not.toThrow();
});
it('handles calls without text property without throwing errors', () => {
// Arrange
renderWithProvider(
<BrowserUrlBar {...propsWithoutUrlBarFocused} ref={urlBarRef} />,
{ state: mockInitialState },
);
// Act & Assert - Should not throw errors when called without text property
expect(() => {
act(() => {
urlBarRef.current?.setNativeProps({ placeholder: 'test' });
});
}).not.toThrow();
});
});
describe('ref interface completeness', () => {
it('exposes all required imperative methods when ref is attached', () => {
// Arrange & Act
renderWithProvider(
<BrowserUrlBar {...defaultProps} ref={urlBarRef} />,
{ state: mockInitialState },
);
// Assert
expect(urlBarRef.current).toBeTruthy();
expect(typeof urlBarRef.current?.hide).toBe('function');
expect(typeof urlBarRef.current?.focus).toBe('function');
expect(typeof urlBarRef.current?.blur).toBe('function');
expect(typeof urlBarRef.current?.setNativeProps).toBe('function');
});
it('handles method calls gracefully without throwing errors', () => {
// Arrange
renderWithProvider(
<BrowserUrlBar {...defaultProps} ref={urlBarRef} />,
{ state: mockInitialState },
);
// Act & Assert - Should not throw errors
expect(() => {
urlBarRef.current?.focus();
urlBarRef.current?.blur();
act(() => {
urlBarRef.current?.setNativeProps({ text: 'test' });
});
act(() => {
urlBarRef.current?.hide();
});
}).not.toThrow();
});
});
});
describe('renderRightButton', () => {
describe('when URL bar is not focused', () => {
it('renders AccountRightButton', () => {
const { getByTestId } = renderWithProvider(
<BrowserUrlBar {...propsWithoutUrlBarFocused} />,
{ state: mockInitialState },
);
const accountButton = getByTestId(
AccountOverviewSelectorsIDs.ACCOUNT_BUTTON,
);
expect(accountButton).toBeDefined();
});
it('calls handleAccountRightButtonPress when account button is pressed', () => {
const { getByTestId } = renderWithProvider(
<BrowserUrlBar {...propsWithoutUrlBarFocused} />,
{ state: mockInitialState },
);
const accountButton = getByTestId(
AccountOverviewSelectorsIDs.ACCOUNT_BUTTON,
);
fireEvent.press(accountButton);
expect(mockTrackEvent).toHaveBeenCalledTimes(2);
expect(mockNavigate).toHaveBeenCalledWith(
Routes.MODAL.ROOT_MODAL_FLOW,
{
screen: Routes.SHEET.ACCOUNT_PERMISSIONS,
params: {
hostInfo: {
metadata: {
origin: 'https://example.com',
},
},
},
},
);
});
});
describe('when URL bar is focused', () => {
it('renders Cancel button with text', () => {
const { getByTestId, getByText } = renderWithProvider(
<BrowserUrlBar {...defaultProps} />,
{ state: mockInitialState },
);
const cancelButton = getByTestId(
BrowserURLBarSelectorsIDs.CANCEL_BUTTON_ON_BROWSER_ID,
);
const cancelText = getByText('Cancel');
expect(cancelButton).toBeDefined();
expect(cancelText).toBeDefined();
});
it('calls onCancel when Cancel button is pressed', () => {
const onCancelMock = jest.fn();
const props = { ...defaultProps, onCancel: onCancelMock };
const { getByTestId } = renderWithProvider(
<BrowserUrlBar {...props} />,
{ state: mockInitialState },
);
const cancelButton = getByTestId(
BrowserURLBarSelectorsIDs.CANCEL_BUTTON_ON_BROWSER_ID,
);
fireEvent.press(cancelButton);
expect(onCancelMock).toHaveBeenCalled();
});
});
describe('button rendering logic', () => {
it('does not render Cancel button when URL bar is not focused', () => {
const { queryByText } = renderWithProvider(
<BrowserUrlBar {...propsWithoutUrlBarFocused} />,
{ state: mockInitialState },
);
const cancelText = queryByText('Cancel');
expect(cancelText).toBeNull();
});
it('always renders Cancel text button when URL bar is focused', () => {
const { getByText } = renderWithProvider(
<BrowserUrlBar {...defaultProps} />,
{ state: mockInitialState },
);
const cancelText = getByText('Cancel');
expect(cancelText).toBeDefined();
});
});
});
describe('Tabs Button', () => {
it('renders tabs button when showTabs prop is provided and URL bar is not focused', () => {
const mockShowTabs = jest.fn();
const { getByTestId } = renderWithProvider(
<BrowserUrlBar
{...propsWithoutUrlBarFocused}
showTabs={mockShowTabs}
/>,
{ state: mockInitialState },
);
const tabsButton = getByTestId('browser-tabs-button');
expect(tabsButton).toBeTruthy();
});
it('calls showTabs when tabs button is pressed', () => {
const mockShowTabs = jest.fn();
const { getByTestId } = renderWithProvider(
<BrowserUrlBar
{...propsWithoutUrlBarFocused}
showTabs={mockShowTabs}
/>,
{ state: mockInitialState },
);
fireEvent.press(getByTestId('browser-tabs-button'));
expect(mockShowTabs).toHaveBeenCalledTimes(1);
});
it('does not render tabs button when showTabs prop is not provided', () => {
const { queryByTestId } = renderWithProvider(
<BrowserUrlBar {...propsWithoutUrlBarFocused} />,
{ state: mockInitialState },
);
const tabsButton = queryByTestId('browser-tabs-button');
expect(tabsButton).toBeNull();
});
it('hides tabs button when URL bar is focused', () => {
const mockShowTabs = jest.fn();
const { queryByTestId } = renderWithProvider(
<BrowserUrlBar {...defaultProps} showTabs={mockShowTabs} />,
{ state: mockInitialState },
);
const tabsButton = queryByTestId('browser-tabs-button');
expect(tabsButton).toBeNull();
});
});
});