Skip to content

Commit

Permalink
test: Refactor Advanced Gas fees test to utilize mocks (#11927)
Browse files Browse the repository at this point in the history
<!--
Please submit this PR as a draft initially.
Do not mark it as "Ready for review" until the template has been
completely filled out, and PR status checks have passed at least once.
-->

## **Description**
The advanced gas fees tests are becoming a bit unstable within the smoke
pipeline mainly because we are relying on real funds (Sepolia ETH) to
submit the transaction. With the recent addition of mocking, we should
refactor the advanced gas fees tests to:

- use ganache
- mock the gas api to return expected values

## **Related issues**

Fixes:

## **Manual testing steps**

1. Go to this page...
2.
3.

## **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**

- [ ] 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).
- [ ] I've completed the PR template to the best of my ability
- [ ] I’ve included tests if applicable
- [ ] I’ve documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [ ] 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.

## **Pre-merge reviewer checklist**

- [ ] 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.

---------

Co-authored-by: Yande <[email protected]>
  • Loading branch information
SamuelSalas and Andepande authored Oct 22, 2024
1 parent 0738030 commit 40f5bef
Show file tree
Hide file tree
Showing 15 changed files with 109 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@ exports[`CustomGasModal should render correctly 1`] = `
"paddingTop": 24,
}
}
testID="edit-priority-legacy-screen"
>
<RCTScrollView
style={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ exports[`EditGasFeeLegacyUpdate should match snapshot 1`] = `
"paddingTop": 24,
}
}
testID="edit-priority-legacy-screen"
>
<RCTScrollView
style={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import { useMetrics } from '../../../../../components/hooks/useMetrics';
import { selectGasFeeEstimates } from '../../../../../selectors/confirmTransaction';
import { selectPrimaryCurrency } from '../../../../../selectors/settings';
import { selectGasFeeControllerEstimateType } from '../../../../../selectors/gasFeeController';
import { EditGasViewSelectorsIDs } from '../../../../../../e2e/selectors/EditGasView.selectors';

const EditGasFeeLegacy = ({
onCancel,
Expand Down Expand Up @@ -254,7 +255,7 @@ const EditGasFeeLegacy = ({
};

return (
<View style={styles.root}>
<View style={styles.root} testID={EditGasViewSelectorsIDs.LEGACY_CONTAINER}>
<ScrollView style={styles.wrapper}>
<TouchableWithoutFeedback>
<View>
Expand Down
5 changes: 5 additions & 0 deletions e2e/fixtures/utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { DEFAULT_GANACHE_PORT } from '../../app/util/test/ganache';
import { DEFAULT_FIXTURE_SERVER_PORT } from './fixture-server';
import { DEFAULT_DAPP_SERVER_PORT } from './fixture-helper';
import { defaultMockPort } from './../mockServer/mockUrlCollection';

function transformToValidPort(defaultPort, pid) {
// Improve uniqueness by using a simple transformation
Expand Down Expand Up @@ -28,3 +29,7 @@ export function getFixturesServerPort() {
export function getLocalTestDappPort() {
return getServerPort(DEFAULT_DAPP_SERVER_PORT);
}

export function getMockttpPort() {
return getServerPort(defaultMockPort);
}
2 changes: 2 additions & 0 deletions e2e/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
getFixturesServerPort,
getGanachePort,
getLocalTestDappPort,
getMockttpPort,
} from './fixtures/utils';
import Utilities from './utils/Utilities';

Expand Down Expand Up @@ -276,6 +277,7 @@ export default class TestHelpers {
await device.reverseTcpPort(getGanachePort());
await device.reverseTcpPort(getFixturesServerPort());
await device.reverseTcpPort(getLocalTestDappPort());
await device.reverseTcpPort(getMockttpPort());
}
}
}
37 changes: 37 additions & 0 deletions e2e/mockServer/data/suggestedGasApiGanacheResponseBody.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"low": {
"suggestedMaxPriorityFeePerGas": "1",
"suggestedMaxFeePerGas": "1.000503137",
"minWaitTimeEstimate": 15000,
"maxWaitTimeEstimate": 60000
},
"medium": {
"suggestedMaxPriorityFeePerGas": "1.5",
"suggestedMaxFeePerGas": "1.500679235",
"minWaitTimeEstimate": 15000,
"maxWaitTimeEstimate": 45000
},
"high": {
"suggestedMaxPriorityFeePerGas": "2",
"suggestedMaxFeePerGas": "2.000855333",
"minWaitTimeEstimate": 15000,
"maxWaitTimeEstimate": 30000
},
"estimatedBaseFee": "0.000503137",
"networkCongestion": 0.34,
"latestPriorityFeeRange": [
"1.5",
"2"
],
"historicalPriorityFeeRange": [
"0.000001",
"236.428872442"
],
"historicalBaseFeeRange": [
"0.000392779",
"0.00100495"
],
"priorityFeeTrend": "up",
"baseFeeTrend": "up",
"version": "0.0.1"
}
25 changes: 15 additions & 10 deletions e2e/mockServer/mockServer.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable no-console */
import { getLocal } from 'mockttp';
import { defaultMockPort } from './mockUrlCollection';
import portfinder from 'portfinder';

const mockServer = getLocal();

Expand All @@ -11,9 +12,10 @@ export const startMockServer = async ({
port = defaultMockPort,
}) => {
if (!mockUrl) throw new Error('The mockUrl parameter is required');

await mockServer.start(port);
console.log(`Mockttp server running at http://localhost:${port}`);
await portfinder.setBasePort(port);
const mockPort = await portfinder.getPortPromise();
await mockServer.start(mockPort);
console.log(`Mockttp server running at http://localhost:${mockPort}`);

await mockServer
.forGet('/health-check')
Expand All @@ -24,17 +26,20 @@ export const startMockServer = async ({
.withQuery({ url: mockUrl })
.thenReply(responseCode, JSON.stringify(responseBody));

await mockServer.forUnmatchedRequest().thenPassThrough({
beforeRequest: async ({ url, method }) => {
console.log(`Forwarding request to: ${method} ${url}`);
return { url: new URL(url).searchParams.get('url') || url };
},
});
await mockServer.forUnmatchedRequest().thenPassThrough({
beforeRequest: async ({ url, method }) => {
const returnUrl = new URL(url).searchParams.get('url') || url;
const updatedUrl = device.getPlatform() === 'android' ? returnUrl.replace('localhost', '127.0.0.1') : returnUrl;

console.log(`Mock proxy forwarding request to: ${updatedUrl}`);
return { url: updatedUrl };
},
});

return mockServer;
};

export const stopMockServer = async () => {
await mockServer.stop();
console.log('Mockttp server stopped');
console.log('Mockttp server shutting down');
};
3 changes: 2 additions & 1 deletion e2e/mockServer/mockUrlCollection.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"localhost": "localhost",
"defaultMockPort": 8000,
"urls": {
"suggestedGasApiMainnet": "'https://gas.api.cx.metamask.io/networks/1/suggestedGasFees'"
"suggestedGasApiMainnet": "https://gas.api.cx.metamask.io/networks/1/suggestedGasFees",
"suggestedGasApiGanache": "https://gas.api.cx.metamask.io/networks/1337/suggestedGasFees"
}
}
9 changes: 8 additions & 1 deletion e2e/pages/Send/AmountView.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import Matchers from '../../utils/Matchers';
import Gestures from '../../utils/Gestures';
import { AmountViewSelectorsIDs } from '../../selectors/SendFlow/AmountView.selectors';
import {
AmountViewSelectorsIDs,
AmountViewSelectorsText
} from '../../selectors/SendFlow/AmountView.selectors';

class AmountView {
get currencySwitch() {
return Matchers.getElementByID(AmountViewSelectorsIDs.CURRENCY_SWITCH);
}

get title() {
return Matchers.getElementByText(AmountViewSelectorsText.SCREEN_TITLE);
}

get nextButton() {
return device.getPlatform() === 'ios'
? Matchers.getElementByID(AmountViewSelectorsIDs.NEXT_BUTTON)
Expand Down
6 changes: 3 additions & 3 deletions e2e/pages/Send/TransactionConfirmView.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ class TransactionConfirmationView {
return Matchers.getElementByText(EditGasViewSelectorsText.ADVANCE_OPTIONS);
}

get editPriorityModal() {
return Matchers.getElementByText(
TransactionConfirmViewSelectorsText.EDIT_PRIORITY_MODAL,
get editPriorityLegacyModal() {
return Matchers.getElementByID(
EditGasViewSelectorsIDs.LEGACY_CONTAINER,
);
}

Expand Down
1 change: 1 addition & 0 deletions e2e/selectors/EditGasView.selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const EditGasViewSelectorsIDs = {
ESTIMATED_FEE_TEST_ID: 'estimated-fee',
EDIT_PRIORITY_SCREEN_TEST_ID: 'edit-priority-screen',
MAX_PRIORITY_FEE_INPUT_TEST_ID: 'max-priority-fee-range-input',
LEGACY_CONTAINER: 'edit-priority-legacy-screen',
};
export const EditGasViewSelectorsText = {
AGGRESSIVE: enContent.edit_gas_fee_eip1559.aggressive,
Expand Down
1 change: 0 additions & 1 deletion e2e/selectors/TransactionConfirmView.selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,4 @@ export const TransactionConfirmViewSelectorsIDs = {

export const TransactionConfirmViewSelectorsText = {
CANCEL_BUTTON: enContent.transaction.cancel,
EDIT_PRIORITY_MODAL: enContent.edit_gas_fee_eip1559.edit_priority,
};
30 changes: 25 additions & 5 deletions e2e/specs/confirmations/advanced-gas-fees.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,42 @@ import TabBarComponent from '../../pages/TabBarComponent';
import WalletActionsModal from '../../pages/modals/WalletActionsModal';
import TestHelpers from '../../helpers';
import Assertions from '../../utils/Assertions';
import { AmountViewSelectorsText } from '../../selectors/SendFlow/AmountView.selectors';
import {
startMockServer,
stopMockServer
} from '../../mockServer/mockServer';
import { urls } from '../../mockServer/mockUrlCollection.json';
import responseBody from '../../mockServer/data/suggestedGasApiGanacheResponseBody.json';

const VALID_ADDRESS = '0xebe6CcB6B55e1d094d9c58980Bc10Fed69932cAb';

describe(SmokeConfirmations('Advanced Gas Fees and Priority Tests'), () => {
let mockServer;
beforeAll(async () => {
jest.setTimeout(170000);
await TestHelpers.reverseServerPort();

mockServer = await startMockServer({ // Configure mock server
mockUrl: urls.suggestedGasApiGanache,
responseCode: 200,
responseBody
});

});

afterAll(async () => {
try {
await stopMockServer();
} catch (error) {
// eslint-disable-next-line no-console
console.log('Mock server already stopped or encountered an error:', error);
}
});

it('should edit priority gas settings and send ETH', async () => {
await withFixtures(
{
fixture: new FixtureBuilder().withSepoliaNetwork().build(),
fixture: new FixtureBuilder().withGanacheNetwork().build(),
restartDevice: true,
ganacheOptions: defaultGanacheOptions,
},
Expand All @@ -46,9 +68,7 @@ describe(SmokeConfirmations('Advanced Gas Fees and Priority Tests'), () => {
await SendView.inputAddress(VALID_ADDRESS);
await SendView.tapNextButton();
// Check that we are on the amount view
await Assertions.checkIfTextIsDisplayed(
AmountViewSelectorsText.SCREEN_TITLE,
);
await Assertions.checkIfVisible(AmountView.title);

// Input acceptable value
await AmountView.typeInTransactionAmount('0.00004');
Expand Down
15 changes: 6 additions & 9 deletions e2e/specs/wallet/suggestedGasApi.mock.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,12 @@ describe(SmokeCore('Mock suggestedGasApi fallback to legacy gas endpoint when E
});
});

// Because we stop the server within the test, a try catch block here would stop the server if the test fails midway
afterAll(async () => {
if (mockServer) {
try {
await stopMockServer(); // Stop the mock server if it's running
} catch (error) {
// eslint-disable-next-line no-console
console.log('Mock server already stopped or encountered an error:', error);
}
try {
await stopMockServer();
} catch (error) {
// eslint-disable-next-line no-console
console.log('Mock server already stopped or encountered an error:', error);
}
});

Expand Down Expand Up @@ -78,7 +75,7 @@ describe(SmokeCore('Mock suggestedGasApi fallback to legacy gas endpoint when E
await AmountView.tapNextButton();
await TransactionConfirmView.tapEstimatedGasLink(1);
await Assertions.checkIfVisible(
TransactionConfirmView.editPriorityModal,
TransactionConfirmView.editPriorityLegacyModal,
);
await stopMockServer(); //stop mock server to reinstate suggested gas api service
await Assertions.checkIfVisible(
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,7 @@
"nyc": "^15.1.0",
"octonode": "0.10.2",
"patch-package": "^6.2.2",
"portfinder": "^1.0.32",
"prettier": "^2.2.1",
"prettier-plugin-gherkin": "^1.1.1",
"react-dom": "18.2.0",
Expand Down

0 comments on commit 40f5bef

Please sign in to comment.