Skip to content

Commit 8d4e444

Browse files
authored
test: stabilize swap deeplink smoke after sendToHome on iOS (MetaMask#29523)
<!-- Please submit this PR as a draft initially. Do not mark it as "Ready for review" until this PR meets the canonical Definition of Ready For Review in `docs/readme/ready-for-review.md`. In short: the template must be materially complete (not just section titles present), all status checks must be currently passing, and the only expected follow-up commits must be reviewer-driven. --> ## **Description** On iOS<16, Detox’s device.sendToHome() brings the home screen to the front. On iOS 16 and later, that path is not used the same way from the simulator tooling, so Detox instead launches and immediately quits the Settings app to put the app under test in the background. That can briefly show Settings and race the next step. This PR tightens tests/smoke/swap/swap-deeplink-smoke.spec.ts: a 1 second wait after sendToHome() before launchApp({ url }), newInstance: false on those launchApp calls so the flow is clearly “same app instance, URL delivered after background,” and short comments above each wait explaining the pre‑16 vs 16+ behavior. ## **Changelog** <!-- If this PR is not End-User-Facing and should not show up in the CHANGELOG, you can choose to either: 1. Write `CHANGELOG entry: null` 2. Label with `no-changelog` If this PR is End-User-Facing, please write a short User-Facing description in the past tense like: `CHANGELOG entry: Added a new tab for users to see their NFTs` `CHANGELOG entry: Fixed a bug that was causing some NFTs to flicker` (This helps the Release Engineer do their job more quickly and accurately) --> CHANGELOG entry: ## **Related issues** Fixes: ## **Manual testing steps** ```gherkin Feature: my feature name Scenario: user [verb for user action] Given [describe expected initial app state] When user [verb for user action] Then [describe expected outcome] ``` ## **Screenshots/Recordings** <!-- If applicable, add screenshots and/or recordings to visualize the before and after of your change. --> ### **Before** <!-- [screenshots/recordings] --> ### **After** <!-- [screenshots/recordings] --> ## **Pre-merge author checklist** <!-- Every checklist item must be consciously assessed before marking this PR as "Ready for review". A checked box means you deliberately considered that responsibility, not that you literally performed every action listed. Unchecked boxes are ambiguous: they are not an implicit "N/A" and they are not a silent "skip". See `docs/readme/ready-for-review.md` for the full checklist semantics. --> - [x] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile Coding Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md). - [x] I've completed the PR template to the best of my ability - [x] I've included tests if applicable - [x] I've documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [x] I've applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. #### Performance checks (if applicable) - [x] I've tested on Android - Ideally on a mid-range device; emulator is acceptable - [x] I've tested with a power user scenario - Use these [power-user SRPs](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/edit-v2/401401446401?draftShareId=9d77e1e1-4bdc-4be1-9ebb-ccd916988d93) to import wallets with many accounts and tokens - [ ] I've instrumented key operations with Sentry traces for production performance metrics - See [`trace()`](/app/util/trace.ts) for usage and [`addToken`](/app/components/Views/AddAsset/components/AddCustomToken/AddCustomToken.tsx#L274) for an example For performance guidelines and tooling, see the [Performance Guide](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/400085549067/Performance+Guide+for+Engineers). ## **Pre-merge reviewer checklist** <!-- Reviewer checklist items follow the same semantics as the author checklist: an unchecked box is ambiguous, a checked box means the reviewer consciously assessed that responsibility. See `docs/readme/ready-for-review.md`. --> - [ ] I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed). - [ ] I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Test-only changes that adjust Detox app launching behavior and add additional HTTP mocks; low risk to production code, with minor risk of masking real integration issues if mock matching is too broad. > > **Overview** > Stabilizes swap deeplink smoke tests on iOS by adding a short post-`sendToHome()` delay and launching deeplinks with `newInstance: false` to ensure URLs are delivered to the existing app instance. > > Expands swap E2E mocking by introducing reusable `setupSwapSocialAndComplianceMocks()` to stub the Social leaderboard and compliance batch endpoints, wiring it into swap and trending-token smoke setups. Also tightens the swap proxy URL interception so the `insufficientBal` rewrite only targets JSON `getQuote` requests (not `getQuoteStream`). > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit edbfe2c. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent 1459869 commit 8d4e444

4 files changed

Lines changed: 80 additions & 1 deletion

File tree

tests/helpers/swap/swap-mocks.ts

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
setupMockRequest,
77
setupSSEMockRequest,
88
} from '../../api-mocking/helpers/mockHelpers';
9+
import { getDecodedProxiedURL } from '../../smoke/notifications/utils/helpers';
910
import {
1011
GET_QUOTE_ETH_USDC_RESPONSE,
1112
GET_QUOTE_ETH_USDC_RESPONSE_CUSTOM_SLIPPAGE,
@@ -30,6 +31,9 @@ const WETH_MAINNET = '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2';
3031
const GOOGLON_MAINNET = '0xba47214edd2bb43099611b208f75e4b42fdcfedc';
3132
const MUSD_MAINNET = '0xaca92e438df0b2401ff60da7e4337b687a2435da';
3233

34+
/** SocialService leaderboard response shape (empty list is valid for E2E). */
35+
const SOCIAL_LEADERBOARD_EMPTY_RESPONSE = { traders: [] };
36+
3337
/**
3438
* Mock spot prices so balance display (balance * price) does not show NaN.
3539
* Shared by swap and bridge E2E tests.
@@ -77,10 +81,64 @@ export async function setupSpotPricesMock(mockServer: Mockttp): Promise<void> {
7781
});
7882
}
7983

84+
/**
85+
* Social leaderboard + compliance batch — used by swap `testSpecificMock` and
86+
* bridge/trending specs that do not use swap-mocks’ full mock bundle.
87+
*/
88+
export async function setupSwapSocialAndComplianceMocks(
89+
mockServer: Mockttp,
90+
): Promise<void> {
91+
await setupMockRequest(
92+
mockServer,
93+
{
94+
requestMethod: 'GET',
95+
url: /social\.api\.cx\.metamask\.io\/api\/v1\/leaderboard/,
96+
response: SOCIAL_LEADERBOARD_EMPTY_RESPONSE,
97+
responseCode: 200,
98+
},
99+
1001,
100+
);
101+
102+
await mockServer
103+
.forPost('/proxy')
104+
.matching((request) => {
105+
try {
106+
const decodedUrl = getDecodedProxiedURL(request.url);
107+
return /compliance\.(dev-api|api|uat-api)\.cx\.metamask\.io\/v1\/wallet\/batch/.test(
108+
decodedUrl,
109+
);
110+
} catch {
111+
return false;
112+
}
113+
})
114+
.asPriority(1001)
115+
.thenCallback(async (request) => {
116+
let addresses: string[] = [];
117+
try {
118+
const text = await request.body.getText();
119+
if (text) {
120+
const parsed = JSON.parse(text) as unknown;
121+
if (Array.isArray(parsed)) {
122+
addresses = parsed.filter(
123+
(a): a is string => typeof a === 'string',
124+
);
125+
}
126+
}
127+
} catch {
128+
/* ignore malformed body */
129+
}
130+
return {
131+
statusCode: 200,
132+
json: addresses.map((address) => ({ address, blocked: false })),
133+
};
134+
});
135+
}
136+
80137
export const testSpecificMock: TestSpecificMock = async (
81138
mockServer: Mockttp,
82139
) => {
83140
await setupSpotPricesMock(mockServer);
141+
await setupSwapSocialAndComplianceMocks(mockServer);
84142

85143
// Catch-all for getQuoteStream with no slippage param (initial render before
86144
// useInitialSlippage fires). Registered first so specific mocks below at
@@ -206,7 +264,10 @@ export const testSpecificMock: TestSpecificMock = async (
206264

207265
await interceptProxyUrl(
208266
mockServer,
209-
(url) => url.includes('getQuote') && url.includes('insufficientBal=false'),
267+
(url) =>
268+
url.includes('getQuote') &&
269+
!url.includes('getQuoteStream') &&
270+
url.includes('insufficientBal=false'),
210271
(url) => url.replace('insufficientBal=false', 'insufficientBal=true'),
211272
);
212273
};

tests/helpers/swap/swap-unified-ui.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
import QuoteView from '../../page-objects/swaps/QuoteView';
22
import SlippageModal from '../../page-objects/swaps/SlippageModal';
33
import { Assertions } from '../../framework';
4+
import { createLogger } from '../../framework/logger';
45
import ActivitiesView from '../../page-objects/Transactions/ActivitiesView';
56
import { ActivitiesViewSelectorsText } from '../../../app/components/Views/ActivityView/ActivitiesView.testIds';
67

8+
const logger = createLogger({ name: 'SwapUnifiedUI' });
9+
710
interface SwapOptions {
811
/** Custom slippage percentage (e.g., "2.5" for 2.5%) */
912
slippage?: string;
@@ -30,9 +33,11 @@ export async function submitSwapUnifiedUI(
3033
await QuoteView.tapDestinationToken();
3134
await QuoteView.tapToken(chainId, destTokenSymbol);
3235

36+
const getQuoteStarted = Date.now();
3337
await Assertions.expectElementToBeVisible(QuoteView.networkFeeLabel, {
3438
timeout: 60000,
3539
});
40+
logger.debug(`⏳ Quote visible after ${Date.now() - getQuoteStarted}ms`);
3641

3742
// Dismiss the keypad so quote details (slippage, confirm) are not obscured
3843
await QuoteView.dismissKeypad();

tests/smoke/swap/swap-deeplink-smoke.spec.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import Assertions from '../../framework/Assertions';
1111
import { asDetoxElement } from '../../framework';
1212
import QuoteView from '../../page-objects/swaps/QuoteView';
1313
import { testSpecificMock } from '../../helpers/swap/swap-mocks';
14+
import TestHelpers from '../../helpers';
1415
import WalletView from '../../page-objects/wallet/WalletView';
1516

1617
// Deep link URLs for testing unified swap/bridge experience
@@ -62,7 +63,10 @@ describe(
6263
async () => {
6364
await loginToApp();
6465
await device.sendToHome();
66+
// intentional: Detox iOS 16+ sendToHome briefly opens Settings; wait before launchApp({ url }).
67+
if (device.getPlatform() === 'ios') await TestHelpers.delay(1000);
6568
await device.launchApp({
69+
newInstance: false,
6670
url: SWAP_DEEPLINK_FULL,
6771
});
6872

@@ -121,7 +125,10 @@ describe(
121125
async () => {
122126
await loginToApp();
123127
await device.sendToHome();
128+
// intentional: Detox iOS 16+ sendToHome briefly opens Settings; wait before launchApp({ url }).
129+
if (device.getPlatform() === 'ios') await TestHelpers.delay(1000);
124130
await device.launchApp({
131+
newInstance: false,
125132
url: SWAP_DEEPLINK_BASE,
126133
});
127134

@@ -175,7 +182,10 @@ describe(
175182
async () => {
176183
await loginToApp();
177184
await device.sendToHome();
185+
// intentional: Detox iOS 16+ sendToHome briefly opens Settings; wait before launchApp({ url }).
186+
if (device.getPlatform() === 'ios') await TestHelpers.delay(1000);
178187
await device.launchApp({
188+
newInstance: false,
179189
url: invalidDeeplink,
180190
});
181191

tests/smoke/swap/swap-trending-tokens.spec.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import TokenOverview from '../../page-objects/wallet/TokenOverview';
1111
import FixtureBuilder from '../../framework/fixtures/FixtureBuilder';
1212
import { prepareSwapsTestEnvironment } from '../../helpers/swap/prepareSwapsTestEnvironment';
1313
import { testSpecificMock } from '../../helpers/swap/bridge-mocks';
14+
import { setupSwapSocialAndComplianceMocks } from '../../helpers/swap/swap-mocks';
1415
import { GET_QUOTE_ETH_USDC_RESPONSE } from '../../helpers/swap/constants';
1516
import { getDecodedProxiedURL } from '../notifications/utils/helpers';
1617
import { SmokeSwap } from '../../tags';
@@ -77,6 +78,8 @@ const setupSwapsTrendingTokensMock = async (mockServer: Mockttp) => {
7778
},
7879
1001,
7980
);
81+
82+
await setupSwapSocialAndComplianceMocks(mockServer);
8083
};
8184

8285
const setupTrendingTokensMock = async (mockServer: Mockttp) => {

0 commit comments

Comments
 (0)