-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathBridgeView.view.test.tsx
More file actions
473 lines (433 loc) · 16.3 KB
/
BridgeView.view.test.tsx
File metadata and controls
473 lines (433 loc) · 16.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
import '../../../../../../tests/component-view/mocks';
import { mockQuoteWithMetadata } from '../../_mocks_/bridgeQuoteWithMetadata';
import { renderBridgeView } from '../../../../../../tests/component-view/renderers/bridge';
import { act, fireEvent, waitFor, within } from '@testing-library/react-native';
import { strings } from '../../../../../../locales/i18n';
import React from 'react';
import { Text } from 'react-native';
import { renderScreenWithRoutes } from '../../../../../../tests/component-view/render';
import Routes from '../../../../../constants/navigation/Routes';
import { initialStateBridge } from '../../../../../../tests/component-view/presets/bridge';
import BridgeView from './index';
import { describeForPlatforms } from '../../../../../../tests/component-view/platform';
import { BridgeViewSelectorsIDs } from './BridgeView.testIds';
import { BuildQuoteSelectors } from '../../../Ramp/Aggregator/Views/BuildQuote/BuildQuote.testIds';
import { CommonSelectorsIDs } from '../../../../../util/Common.testIds';
import { setSlippage } from '../../../../../core/redux/slices/bridge';
import { BridgeTokenSelector } from '../../components/BridgeTokenSelector/BridgeTokenSelector';
import Engine from '../../../../../core/Engine';
import type { DeepPartial } from '../../../../../util/test/renderWithProvider';
import type { RootState } from '../../../../../reducers';
import { RequestStatus } from '@metamask/bridge-controller';
import {
DEFAULT_BRIDGE,
ETH_SOURCE,
USDC_DEST,
} from '../../_mocks_/bridgeViewTestConstants';
const defaultBridgeWithTokens = (overrides?: Record<string, unknown>) => {
const { bridge: bridgeOverrides, ...rest } = overrides ?? {};
return renderBridgeView({
deterministicFiat: true,
overrides: {
bridge: {
...DEFAULT_BRIDGE,
...(bridgeOverrides as Record<string, unknown>),
},
...rest,
} as unknown as DeepPartial<RootState>,
});
};
describeForPlatforms('BridgeView', () => {
beforeEach(() => {
// testSetup.js mocks Date.now to always return 123, which breaks lodash debounce
// (timeSinceLastCall = 123 - 123 = 0 never reaches the wait threshold).
// Restore it to a real implementation so debounce-based tests work correctly.
Date.now = () => new Date().getTime();
});
it('renders input areas and hides confirm button without tokens or amount', () => {
const { getByTestId, queryByTestId } = renderBridgeView({
overrides: {
engine: {
backgroundState: {
BridgeController: {
state: { quotesLastFetched: 0 },
},
},
},
} as unknown as Record<string, unknown>,
});
expect(
getByTestId(BridgeViewSelectorsIDs.SOURCE_TOKEN_AREA),
).toBeOnTheScreen();
expect(
getByTestId(BridgeViewSelectorsIDs.DESTINATION_TOKEN_AREA),
).toBeOnTheScreen();
expect(queryByTestId(BridgeViewSelectorsIDs.CONFIRM_BUTTON)).toBeNull();
});
it('types 9.5 with keypad and displays $19,000.00 fiat value', async () => {
const {
getByTestId,
queryByTestId,
getByText,
findByText,
findByDisplayValue,
} = defaultBridgeWithTokens({
bridge: {
sourceAmount: '0',
sourceToken: ETH_SOURCE,
destToken: undefined,
},
} as unknown as Record<string, unknown>);
const closeBanner = queryByTestId(
CommonSelectorsIDs.BANNER_CLOSE_BUTTON_ICON,
);
if (closeBanner) {
fireEvent.press(closeBanner);
}
const sourceInput = getByTestId(BridgeViewSelectorsIDs.SOURCE_TOKEN_INPUT);
fireEvent(sourceInput, 'pressIn');
// Keypad opens on source input interaction
await waitFor(() => {
expect(
getByTestId(BuildQuoteSelectors.KEYPAD_DELETE_BUTTON),
).toBeOnTheScreen();
});
// Keypad is in SwapsKeypad (sibling of ScrollView), not inside bridge-view-scroll
fireEvent.press(getByText('9'));
fireEvent.press(getByText('.'));
fireEvent.press(getByText('5'));
expect(await findByDisplayValue('9.5')).toBeOnTheScreen();
expect(await findByText('$19,000.00')).toBeOnTheScreen();
});
it('renders enabled confirm button with tokens, amount and recommended quote', () => {
const now = Date.now();
const { getAllByTestId } = defaultBridgeWithTokens({
engine: {
backgroundState: {
BridgeController: {
quotes: [
mockQuoteWithMetadata as unknown as Record<string, unknown>,
],
recommendedQuote: mockQuoteWithMetadata as unknown as Record<
string,
unknown
>,
quotesLastFetched: now,
quotesLoadingStatus: RequestStatus.FETCHED,
quoteFetchError: null,
},
},
},
} as unknown as Record<string, unknown>);
// The confirm button may render in both the bottom content area and inside
// the SwapsKeypad (which stays open until the user taps outside the input).
const buttons = getAllByTestId(BridgeViewSelectorsIDs.CONFIRM_BUTTON);
expect(buttons.length).toBeGreaterThanOrEqual(1);
expect(buttons[0]).toBeOnTheScreen();
expect(
(buttons[0] as unknown as { props: { isDisabled?: boolean } }).props
.isDisabled,
).not.toBe(true);
});
it('stores custom slippage when user sets 5%', async () => {
const { store } = defaultBridgeWithTokens({
bridge: { selectedDestChainId: '0x1' },
engine: {
backgroundState: {
BridgeController: {
quotesLastFetched: 0,
quotes: [],
quotesLoadingStatus: null,
quoteFetchError: null,
},
},
},
} as unknown as Record<string, unknown>);
act(() => {
store.dispatch(setSlippage('5'));
});
await waitFor(
() => {
expect(store.getState().bridge.slippage).toBe('5');
},
{ timeout: 1000 },
);
});
it('navigates to dest token selector on press', async () => {
const TokenSelectorProbe: React.FC<{
route?: { params?: { type?: string } };
}> = (props) => (
<Text testID="token-selector-probe">{props?.route?.params?.type}</Text>
);
const state = initialStateBridge()
.withOverrides({
bridge: { sourceToken: ETH_SOURCE },
} as unknown as Record<string, unknown>)
.build() as unknown as Record<string, unknown>;
const { findByText } = renderScreenWithRoutes(
BridgeView as unknown as React.ComponentType,
{ name: Routes.BRIDGE.ROOT },
[
{
name: Routes.BRIDGE.TOKEN_SELECTOR,
Component:
TokenSelectorProbe as unknown as React.ComponentType<unknown>,
},
],
{ state },
);
fireEvent.press(await findByText('Swap to'));
expect(await findByText('dest')).toBeOnTheScreen();
});
describe('Swap team regression (bug matrix team-swaps-and-bridge)', () => {
/** Issues covered: #24744, #24865, #24802, #25256 */
// eslint-disable-next-line @metamask/design-tokens/color-no-hex -- "#24744" style references are GitHub issue IDs (e.g. "#2342"), not color literals
it('displays gas included label and enables confirm when quote has gas included (#24744)', async () => {
const now = Date.now();
const quoteWithGasIncluded = {
...(mockQuoteWithMetadata as unknown as Record<string, unknown>),
};
const innerQuote =
(quoteWithGasIncluded.quote as Record<string, unknown>) ?? {};
quoteWithGasIncluded.quote = {
...innerQuote,
gasIncluded: true,
srcChainId: 1,
destChainId: 1,
};
const { getByTestId, findByText } = defaultBridgeWithTokens({
engine: {
backgroundState: {
BridgeController: {
quotes: [quoteWithGasIncluded],
recommendedQuote: quoteWithGasIncluded,
quotesLastFetched: now,
quotesLoadingStatus: RequestStatus.FETCHED,
quoteFetchError: null,
},
},
},
} as unknown as Record<string, unknown>);
expect(await findByText(strings('bridge.included'))).toBeOnTheScreen();
const confirmButton = getByTestId(BridgeViewSelectorsIDs.CONFIRM_BUTTON);
expect(confirmButton).toBeOnTheScreen();
expect(
(confirmButton as unknown as { props: { isDisabled?: boolean } }).props
.isDisabled,
).not.toBe(true);
});
// Regression for #25256: two USDT tokens on Linea must both appear in search results.
// eslint-disable-next-line @metamask/design-tokens/color-no-hex -- "#25256" style references are GitHub issue IDs (e.g. "#2342"), not color literals
it('shows two USDT when search API returns two USDT on Linea (#25256)', async () => {
jest
.spyOn(Engine.context.AuthenticationController, 'getBearerToken')
.mockResolvedValue('mock-bearer-token');
const LINEA_CHAIN_ID = 59144;
const verifiedUsdtAddress = '0xA219439258ca9da29E9Cc4cE5596924745e12B93';
const otherUsdtAddress = '0x0000000000000000000000000000000000000001';
const twoLineaUsdtTokens = [
{
assetId: `eip155:${LINEA_CHAIN_ID}/erc20:${verifiedUsdtAddress}`,
decimals: 6,
iconUrl: '',
name: 'Tether USD',
symbol: 'USDT',
},
{
assetId: `eip155:${LINEA_CHAIN_ID}/erc20:${otherUsdtAddress}`,
decimals: 6,
iconUrl: '',
name: 'Tether USD (duplicate)',
symbol: 'USDT',
},
];
const searchResponse = {
data: twoLineaUsdtTokens,
count: 2,
totalCount: 2,
pageInfo: { hasNextPage: false },
};
const fetchSpy = jest
.spyOn(globalThis, 'fetch')
.mockImplementation((url, init) => {
const urlStr =
typeof url === 'string' ? url : (url as URL).toString();
if (urlStr.includes('/getTokens/search')) {
let body: { query?: string } = {};
try {
const rawBody = (init as RequestInit)?.body;
body = typeof rawBody === 'string' ? JSON.parse(rawBody) : {};
} catch {
// ignore parse errors
}
if (body.query === 'USDT') {
return Promise.resolve({
ok: true,
json: () => Promise.resolve(searchResponse),
} as Response);
}
return Promise.resolve({
ok: true,
json: () =>
Promise.resolve({
data: [],
count: 0,
totalCount: 0,
pageInfo: { hasNextPage: false },
}),
} as Response);
}
if (urlStr.includes('/getTokens/popular')) {
return Promise.resolve({
ok: true,
json: () => Promise.resolve([]),
} as Response);
}
return Promise.reject(new Error(`Unmocked fetch: ${urlStr}`));
});
const state = initialStateBridge({ deterministicFiat: true })
.withMinimalTokensController(['0x1', '0xe708'])
.withOverrides({
bridge: {
sourceToken: ETH_SOURCE,
},
engine: {
backgroundState: {
RemoteFeatureFlagController: {
remoteFeatureFlags: {
bridgeConfigV2: {
minimumVersion: '0.0.0',
maxRefreshCount: 5,
refreshRate: 30000,
support: true,
chains: {},
chainRanking: [
{ chainId: 'eip155:1', name: 'Ethereum' },
{ chainId: 'eip155:59144', name: 'Linea' },
],
},
},
},
NetworkController: {
networkConfigurationsByChainId: {
'0xe708': {
chainId: '0xe708',
rpcEndpoints: [
{
networkClientId: 'linea-mainnet',
url: 'https://rpc.linea.build',
type: 'rpc',
name: 'Linea',
},
],
defaultRpcEndpointIndex: 0,
blockExplorerUrls: ['https://lineascan.build'],
defaultBlockExplorerUrlIndex: 0,
name: 'Linea Mainnet',
nativeCurrency: 'ETH',
},
},
},
TokenBalancesController: {
tokenBalances: {},
},
PreferencesController: {
tokenSortConfig: {
key: 'tokenFiatAmount',
order: 'dsc',
},
},
},
},
} as unknown as Record<string, unknown>)
.build() as unknown as Record<string, unknown>;
const { getByTestId, getByText, findByText, getAllByText } =
renderScreenWithRoutes(
BridgeView as unknown as React.ComponentType,
{ name: Routes.BRIDGE.BRIDGE_VIEW },
[
{
name: Routes.BRIDGE.TOKEN_SELECTOR,
Component:
BridgeTokenSelector as unknown as React.ComponentType<unknown>,
},
],
{ state },
);
fireEvent.press(await findByText('Swap to'));
const searchInput = await waitFor(
() => getByTestId('bridge-token-search-input'),
{ timeout: 5000 },
);
fireEvent.changeText(searchInput, 'USDT');
// Force immediate re-search by changing network with an active query.
// BridgeTokenSelector calls `searchTokens(searchString)` on chain switch.
fireEvent.press(getByText('Linea'));
// Wait for list to show results (second token has unique name)
await waitFor(
() => {
expect(getByText('Tether USD (duplicate)')).toBeOnTheScreen();
},
{ timeout: 10000 },
);
const usdtLabels = getAllByText('USDT');
expect(usdtLabels.length).toBe(2);
fetchSpy.mockRestore();
}, 25000);
// eslint-disable-next-line @metamask/design-tokens/color-no-hex -- "#24865" style references are GitHub issue IDs (e.g. "#2342"), not color literals
it('shows native token in source area when source is native token from token details (#24865)', () => {
const bnbChainId = '0x38';
const nativeBnbAddress = '0x0000000000000000000000000000000000000000';
const { getByTestId } = defaultBridgeWithTokens({
bridge: {
sourceAmount: '1',
sourceToken: {
address: nativeBnbAddress,
chainId: bnbChainId,
decimals: 18,
symbol: 'BNB',
name: 'BNB',
},
destToken: undefined,
},
} as unknown as Record<string, unknown>);
const sourceArea = getByTestId(BridgeViewSelectorsIDs.SOURCE_TOKEN_AREA);
const destArea = getByTestId(
BridgeViewSelectorsIDs.DESTINATION_TOKEN_AREA,
);
expect(sourceArea).toBeOnTheScreen();
expect(destArea).toBeOnTheScreen();
expect(within(sourceArea).getByText('BNB')).toBeOnTheScreen();
});
// eslint-disable-next-line @metamask/design-tokens/color-no-hex -- "#24802" style references are GitHub issue IDs (e.g. "#2342"), not color literals
it('renders USDC to BNB swap setup without crash and hides confirm when no quote (#24802)', () => {
const bnbChainIdHex = '0x38';
const { getByTestId, queryByTestId } = defaultBridgeWithTokens({
bridge: {
sourceAmount: '100',
sourceToken: USDC_DEST,
destToken: undefined,
selectedDestChainId: bnbChainIdHex,
},
engine: {
backgroundState: {
BridgeController: {
quotes: [],
recommendedQuote: null,
quotesLastFetched: 0,
quotesLoadingStatus: null,
quoteFetchError: null,
},
},
},
} as unknown as Record<string, unknown>);
expect(
getByTestId(BridgeViewSelectorsIDs.SOURCE_TOKEN_AREA),
).toBeOnTheScreen();
expect(
getByTestId(BridgeViewSelectorsIDs.DESTINATION_TOKEN_AREA),
).toBeOnTheScreen();
expect(queryByTestId(BridgeViewSelectorsIDs.CONFIRM_BUTTON)).toBeNull();
});
});
});