-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathCheckout.test.tsx
More file actions
560 lines (479 loc) · 16.8 KB
/
Checkout.test.tsx
File metadata and controls
560 lines (479 loc) · 16.8 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
/* eslint-disable @metamask/design-tokens/color-no-hex -- theme mock uses hex for test compatibility */
import React from 'react';
import { fireEvent, act, waitFor } from '@testing-library/react-native';
import Checkout from './Checkout';
import renderWithProvider from '../../../../../util/test/renderWithProvider';
import { MetaMetricsEvents } from '../../../../../core/Analytics';
import Routes from '../../../../../constants/navigation/Routes';
import { callbackBaseUrl } from '../../Aggregator/sdk';
jest.mock('@react-navigation/native', () => {
const actual = jest.requireActual('@react-navigation/native');
return {
...actual,
useNavigation: jest.fn(),
};
});
const mockDispatch = jest.fn();
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useDispatch: jest.fn(() => mockDispatch),
}));
jest.mock('../../../../../util/navigation/navUtils', () => ({
useParams: jest.fn(),
createNavigationDetails: jest.fn((_root: string, screen: string) => ({
name: screen,
params: {},
})),
}));
jest.mock('../../hooks/useRampsOrders', () => ({
useRampsOrders: jest.fn(),
}));
jest.mock('../../../../hooks/useAnalytics/useAnalytics', () => ({
useAnalytics: jest.fn(),
}));
jest.mock('../../../../../actions/user', () => ({
protectWalletModalVisible: jest.fn(() => ({
type: 'PROTECT_WALLET_MODAL_VISIBLE',
})),
}));
jest.mock('../../../../../reducers/fiatOrders', () => ({
getRampRoutingDecision: () => null,
}));
jest.mock('../../../../../util/Logger', () => ({
error: jest.fn(),
log: jest.fn(),
}));
jest.mock('../../../../../util/browser', () => ({
shouldStartLoadWithRequest: jest.fn(() => true),
}));
jest.mock('../../Aggregator/sdk', () => ({
callbackBaseUrl:
'https://on-ramp-content.api.cx.metamask.io/regions/fake-callback',
useRampSDK: jest.fn(() => null),
}));
let capturedOnNavigationStateChange:
| ((state: { url: string; loading?: boolean }) => void)
| undefined;
jest.mock('@metamask/react-native-webview', () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires -- jest mock factory
const { View, Button } = require('react-native');
const getCallbackBaseUrl = () =>
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires -- resolve mocked sdk at press time (avoids jest hoist / TDZ with outer consts)
require('../../Aggregator/sdk').callbackBaseUrl as string;
return {
WebView: ({
onNavigationStateChange,
onHttpError,
onShouldStartLoadWithRequest,
testID,
}: {
onNavigationStateChange?: (state: {
url: string;
loading?: boolean;
}) => void;
onHttpError?: (e: {
nativeEvent: { url: string; statusCode: number };
}) => void;
onShouldStartLoadWithRequest?: (req: { url: string }) => boolean;
testID?: string;
}) => {
capturedOnNavigationStateChange = onNavigationStateChange;
return (
<View testID={testID ?? 'checkout-webview'}>
<Button
testID="trigger-callback-navigation"
title="TriggerCallback"
onPress={() =>
onNavigationStateChange?.({
url: `${getCallbackBaseUrl()}?orderId=123`,
loading: false,
})
}
/>
<Button
testID="trigger-callback-empty-query"
title="TriggerCallbackEmptyQuery"
onPress={() =>
onNavigationStateChange?.({
url: getCallbackBaseUrl(),
loading: false,
})
}
/>
<Button
testID="trigger-callback-loading"
title="TriggerCallbackLoading"
onPress={() =>
onNavigationStateChange?.({
url: `${getCallbackBaseUrl()}?orderId=123`,
loading: true,
})
}
/>
<Button
testID="trigger-dedup-navigation"
title="TriggerDedup"
onPress={() =>
onNavigationStateChange?.({
url: 'https://custom-dedup-url.example.com',
loading: false,
})
}
/>
<Button
testID="trigger-http-error-main-uri"
title="TriggerHttpError"
onPress={() =>
onHttpError?.({
nativeEvent: {
url: 'https://provider.example.com/checkout',
statusCode: 502,
},
})
}
/>
<Button
testID="trigger-http-error-auxiliary"
title="TriggerHttpErrorAux"
onPress={() =>
onHttpError?.({
nativeEvent: {
url: 'https://cdn.example.com/asset.woff2',
statusCode: 404,
},
})
}
/>
<Button
testID="trigger-should-start-load"
title="TriggerShouldStartLoad"
onPress={() =>
onShouldStartLoadWithRequest?.({
url: 'https://provider.example.com/next-hop',
})
}
/>
</View>
);
},
};
});
const mockUseParams = jest.requireMock(
'../../../../../util/navigation/navUtils',
).useParams as jest.Mock;
const mockUseRampsOrders = jest.requireMock('../../hooks/useRampsOrders')
.useRampsOrders as jest.Mock;
const mockUseAnalytics = jest.requireMock(
'../../../../hooks/useAnalytics/useAnalytics',
).useAnalytics as jest.Mock;
const mockTrackEvent = jest.fn();
const mockCreateEventBuilder = jest.fn();
const mockAddProperties = jest.fn();
const mockBuild = jest.fn();
describe('Checkout', () => {
const mockAddPrecreatedOrder = jest.fn();
const mockNavigation = {
setOptions: jest.fn(),
reset: jest.fn(),
goBack: jest.fn(),
isFocused: jest.fn(() => true),
dangerouslyGetParent: jest.fn(() => ({ pop: jest.fn() })),
getParent: jest.fn(() => ({ pop: jest.fn() })),
};
beforeEach(() => {
jest.clearAllMocks();
mockUseParams.mockReturnValue({
url: 'https://provider.example.com/checkout',
providerName: 'Test Provider',
});
mockUseRampsOrders.mockReturnValue({
addPrecreatedOrder: mockAddPrecreatedOrder,
});
mockUseAnalytics.mockReturnValue({
trackEvent: mockTrackEvent,
createEventBuilder: mockCreateEventBuilder,
});
mockCreateEventBuilder.mockReturnValue({
addProperties: mockAddProperties,
build: mockBuild,
});
mockAddProperties.mockReturnValue({ build: mockBuild });
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires -- jest mock
const nav = require('@react-navigation/native');
nav.useNavigation.mockReturnValue(mockNavigation);
mockNavigation.getParent.mockReset();
mockNavigation.getParent.mockImplementation(() => ({ pop: jest.fn() }));
});
describe('handleNavigationStateChange (callback flow)', () => {
const callbackFlowParams = {
url: 'https://provider.example.com/checkout',
providerName: 'Test Provider',
providerCode: 'moonpay',
walletAddress: '0x1234567890abcdef',
};
it('returns early when navState.loading is true', () => {
mockUseParams.mockReturnValue(callbackFlowParams);
renderWithProvider(<Checkout />, {}, true, false);
act(() => {
capturedOnNavigationStateChange?.({
url: `${callbackBaseUrl}?orderId=123`,
loading: true,
});
});
expect(mockNavigation.reset).not.toHaveBeenCalled();
});
it('does not invoke callback handler when hasCallbackFlow is false', async () => {
mockUseParams.mockReturnValue({
url: 'https://provider.example.com',
providerName: 'Test',
});
const { getByTestId } = renderWithProvider(<Checkout />, {}, true, false);
await act(async () => {
fireEvent.press(getByTestId('trigger-callback-navigation'));
});
expect(mockNavigation.reset).not.toHaveBeenCalled();
});
});
describe('close button analytics (280-288)', () => {
it('tracks RAMPS_CLOSE_BUTTON_CLICKED when close button is pressed', () => {
mockUseParams.mockReturnValue({
url: 'https://provider.example.com',
providerName: 'Test',
});
const { getByTestId } = renderWithProvider(<Checkout />, {}, true, false);
fireEvent.press(getByTestId('checkout-close-button'));
expect(mockCreateEventBuilder).toHaveBeenCalled();
expect(mockAddProperties).toHaveBeenCalledWith(
expect.objectContaining({
location: 'Checkout',
ramp_type: 'UNIFIED_BUY_2',
}),
);
expect(mockTrackEvent).toHaveBeenCalled();
});
});
describe('onNavigationStateChange with URL deduplication', () => {
it('invokes param callback when WebView navigates to new URL', async () => {
const mockCallback = jest.fn();
mockUseParams.mockReturnValue({
url: 'https://provider.example.com',
providerName: 'Test',
onNavigationStateChange: mockCallback,
});
const { getByTestId } = renderWithProvider(<Checkout />, {}, true, false);
await act(async () => {
fireEvent.press(getByTestId('trigger-dedup-navigation'));
});
expect(mockCallback).toHaveBeenCalledWith(
expect.objectContaining({
url: 'https://custom-dedup-url.example.com',
}),
);
});
it('does not invoke callback on second navigation to same URL (dedup)', async () => {
const mockCallback = jest.fn();
mockUseParams.mockReturnValue({
url: 'https://provider.example.com',
providerName: 'Test',
onNavigationStateChange: mockCallback,
});
const { getByTestId } = renderWithProvider(<Checkout />, {}, true, false);
await act(async () => {
fireEvent.press(getByTestId('trigger-dedup-navigation'));
fireEvent.press(getByTestId('trigger-dedup-navigation'));
});
expect(mockCallback).toHaveBeenCalledTimes(1);
});
});
describe('WebView HTTP error and error recovery', () => {
it('sets error when main checkout URL returns HTTP error', async () => {
mockUseParams.mockReturnValue({
url: 'https://provider.example.com/checkout',
providerName: 'Test Provider',
});
const { getByTestId, getByText } = renderWithProvider(
<Checkout />,
{},
true,
false,
);
await act(async () => {
fireEvent.press(getByTestId('trigger-http-error-main-uri'));
});
expect(
getByText('WebView received error status code: 502'),
).toBeOnTheScreen();
});
it('clears error when Try again is pressed after HTTP error', async () => {
mockUseParams.mockReturnValue({
url: 'https://provider.example.com/checkout',
providerName: 'Test Provider',
});
const { getByTestId, getByText } = renderWithProvider(
<Checkout />,
{},
true,
false,
);
await act(async () => {
fireEvent.press(getByTestId('trigger-http-error-main-uri'));
});
await act(async () => {
fireEvent.press(getByText('Try again'));
});
expect(getByTestId('checkout-webview')).toBeOnTheScreen();
});
});
describe('addPrecreatedOrder registration', () => {
it('registers precreated order when orderId and callback flow params are present', async () => {
mockUseParams.mockReturnValue({
url: 'https://provider.example.com/checkout',
providerName: 'MoonPay',
providerCode: 'moonpay',
walletAddress: '0xabcdef1234567890',
orderId: 'mp-order-99',
network: 'eip155:1',
});
renderWithProvider(<Checkout />, {}, true, false);
await waitFor(() => {
expect(mockAddPrecreatedOrder).toHaveBeenCalledWith({
orderId: 'mp-order-99',
providerCode: 'moonpay',
walletAddress: '0xabcdef1234567890',
chainId: 'eip155:1',
});
});
});
});
describe('missing checkout URL', () => {
it('renders ErrorView when url is not provided', () => {
mockUseParams.mockReturnValue({
providerName: 'Test Provider',
});
const { getByText } = renderWithProvider(<Checkout />, {}, true, false);
expect(getByText('No URL was provided to continue')).toBeOnTheScreen();
});
});
describe('screen view analytics', () => {
it('tracks RAMPS_SCREEN_VIEWED when checkout WebView mounts', () => {
mockUseParams.mockReturnValue({
url: 'https://provider.example.com/checkout',
providerName: 'Test',
});
renderWithProvider(<Checkout />, {}, true, false);
expect(mockCreateEventBuilder).toHaveBeenCalledWith(
MetaMetricsEvents.RAMPS_SCREEN_VIEWED,
);
});
});
describe('auxiliary WebView HTTP errors', () => {
it('logs non-fatal HTTP errors for auxiliary resource URLs', async () => {
const Logger = jest.requireMock('../../../../../util/Logger') as {
log: jest.Mock;
};
mockUseParams.mockReturnValue({
url: 'https://provider.example.com/checkout',
providerName: 'Test',
});
const { getByTestId } = renderWithProvider(<Checkout />, {}, true, false);
await act(async () => {
fireEvent.press(getByTestId('trigger-http-error-auxiliary'));
});
expect(Logger.log).toHaveBeenCalledWith(
expect.stringContaining('Checkout: HTTP error 404'),
);
});
});
describe('callback success (unified buy stack)', () => {
it('resets navigation to order details with callback params without fetching the order in Checkout', async () => {
const callbackUrl = `${callbackBaseUrl}?orderId=123`;
mockUseParams.mockReturnValue({
url: 'https://provider.example.com/checkout',
providerName: 'Test',
providerCode: 'moonpay',
walletAddress: '0xabc',
cryptocurrency: 'ETH',
});
const { getByTestId } = renderWithProvider(<Checkout />, {}, true, false);
await act(async () => {
fireEvent.press(getByTestId('trigger-callback-navigation'));
});
await waitFor(() => {
expect(mockNavigation.reset).toHaveBeenCalledWith({
index: 0,
routes: [
{
name: Routes.RAMP.RAMPS_ORDER_DETAILS,
params: {
callbackUrl,
providerCode: 'moonpay',
walletAddress: '0xabc',
showCloseButton: true,
cryptocurrency: 'ETH',
},
},
],
});
});
});
});
describe('customOrderId fallback', () => {
it('uses customOrderId when orderId is not provided', async () => {
mockUseParams.mockReturnValue({
url: 'https://provider.example.com/checkout',
providerName: 'Test',
providerCode: 'transak',
walletAddress: '0xdef',
customOrderId: 'custom-id-42',
network: 'eip155:1',
});
renderWithProvider(<Checkout />, {}, true, false);
await waitFor(() => {
expect(mockAddPrecreatedOrder).toHaveBeenCalledWith(
expect.objectContaining({
orderId: 'custom-id-42',
}),
);
});
});
});
describe('callback empty query pop', () => {
it('pops parent when callback URL has no query params', async () => {
const mockParentPop = jest.fn();
mockNavigation.getParent.mockReturnValue({ pop: mockParentPop });
mockUseParams.mockReturnValue({
url: 'https://provider.example.com/checkout',
providerName: 'Test',
providerCode: 'moonpay',
walletAddress: '0xabc',
});
const { getByTestId } = renderWithProvider(<Checkout />, {}, true, false);
await act(async () => {
fireEvent.press(getByTestId('trigger-callback-empty-query'));
});
expect(mockNavigation.getParent).toHaveBeenCalled();
expect(mockParentPop).toHaveBeenCalled();
});
});
describe('onShouldStartLoadWithRequest', () => {
it('delegates to shouldStartLoadWithRequest with the request URL and Logger', () => {
const { shouldStartLoadWithRequest } = jest.requireMock(
'../../../../../util/browser',
) as { shouldStartLoadWithRequest: jest.Mock };
const Logger = jest.requireMock('../../../../../util/Logger') as {
error: jest.Mock;
log: jest.Mock;
};
mockUseParams.mockReturnValue({
url: 'https://provider.example.com/checkout',
providerName: 'Test',
});
const { getByTestId } = renderWithProvider(<Checkout />, {}, true, false);
fireEvent.press(getByTestId('trigger-should-start-load'));
expect(shouldStartLoadWithRequest).toHaveBeenCalledWith(
'https://provider.example.com/next-hop',
Logger,
);
});
});
});