Skip to content

Commit

Permalink
test: Enable type checking of tests (#24844)
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**

Most tests were not being type-checked by the `yarn lint:tsc` command
because they were omitted from `tsconfig.json`. `tsconfig.json` has been
updated to include tests, and all affected files were updated to fix
resulting ESLint and type errors.

[![Open in GitHub
Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/MetaMask/metamask-extension/pull/24844?quickstart=1)

## **Related issues**

N/A

## **Manual testing steps**

N/A

## **Screenshots/Recordings**

N/A

## **Pre-merge author checklist**

- [x] I’ve followed [MetaMask Coding
Standards](https://github.com/MetaMask/metamask-extension/blob/develop/.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-extension/blob/develop/.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.
  • Loading branch information
Gudahtt authored Jun 3, 2024
1 parent 48faea7 commit 63851c9
Show file tree
Hide file tree
Showing 56 changed files with 2,420 additions and 1,842 deletions.
6 changes: 5 additions & 1 deletion app/scripts/controllers/encryption-public-key.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,14 +214,18 @@ describe('EncryptionPublicKeyController', () => {
});

describe('newRequestEncryptionPublicKey', () => {
// @ts-expect-error This function is missing from the Mocha type definitions
it.each([
['Ledger', KeyringType.ledger],
['Trezor', KeyringType.trezor],
['Lattice', KeyringType.lattice],
['QR hardware', KeyringType.qr],
])(
'throws if keyring is not supported',
async (keyringName, keyringType) => {
async (
keyringName: string,
keyringType: (typeof KeyringType)[keyof typeof KeyringType],
) => {
getAccountKeyringTypeMock.mockResolvedValueOnce(keyringType);

await expect(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ const rawNotificationTestSuite = rawNotifications.map(
);

describe('process-onchain-notifications - processOnChainNotification()', () => {
// @ts-expect-error This is missing from the Mocha type definitions
test.each(rawNotificationTestSuite)(
'Converts Raw On-Chain Notification (%s) to a shared Notification Type',
(_, rawNotification) => {
(_: string, rawNotification: OnChainRawNotification) => {
const result = processOnChainNotification(rawNotification);
expect(result.id).toBe(rawNotification.id);
expect(result.type).toBe(rawNotification.type);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ describe('user-storage/user-storage-controller - performGetStorage() tests', ()
).rejects.toThrow();
});

// @ts-expect-error This is missing from the Mocha type definitions
test.each([
[
'fails when no bearer token is found (auth errors)',
Expand All @@ -88,18 +89,26 @@ describe('user-storage/user-storage-controller - performGetStorage() tests', ()
new Error('MOCK FAILURE'),
),
],
])('rejects on auth failure - %s', async (_, arrangeFailureCase) => {
const { messengerMocks } = arrangeMocks();
arrangeFailureCase(messengerMocks);
const controller = new UserStorageController({
messenger: messengerMocks.messenger,
getMetaMetricsState: () => true,
});

await expect(
controller.performGetStorage('notification_settings'),
).rejects.toThrow();
});
])(
'rejects on auth failure - %s',
async (
_: string,
arrangeFailureCase: (
messengerMocks: ReturnType<typeof mockUserStorageMessenger>,
) => void,
) => {
const { messengerMocks } = arrangeMocks();
arrangeFailureCase(messengerMocks);
const controller = new UserStorageController({
messenger: messengerMocks.messenger,
getMetaMetricsState: () => true,
});

await expect(
controller.performGetStorage('notification_settings'),
).rejects.toThrow();
},
);

function arrangeMocks() {
return {
Expand Down Expand Up @@ -137,6 +146,7 @@ describe('user-storage/user-storage-controller - performSetStorage() tests', ()
).rejects.toThrow();
});

// @ts-expect-error This is missing from the Mocha type definitions
test.each([
[
'fails when no bearer token is found (auth errors)',
Expand All @@ -152,18 +162,26 @@ describe('user-storage/user-storage-controller - performSetStorage() tests', ()
new Error('MOCK FAILURE'),
),
],
])('rejects on auth failure - %s', async (_, arrangeFailureCase) => {
const { messengerMocks } = arrangeMocks();
arrangeFailureCase(messengerMocks);
const controller = new UserStorageController({
messenger: messengerMocks.messenger,
getMetaMetricsState: () => true,
});

await expect(
controller.performSetStorage('notification_settings', 'new data'),
).rejects.toThrow();
});
])(
'rejects on auth failure - %s',
async (
_: string,
arrangeFailureCase: (
messengerMocks: ReturnType<typeof mockUserStorageMessenger>,
) => void,
) => {
const { messengerMocks } = arrangeMocks();
arrangeFailureCase(messengerMocks);
const controller = new UserStorageController({
messenger: messengerMocks.messenger,
getMetaMetricsState: () => true,
});

await expect(
controller.performSetStorage('notification_settings', 'new data'),
).rejects.toThrow();
},
);

test('rejects if api call fails', async () => {
const { messengerMocks } = arrangeMocks({
Expand Down
9 changes: 8 additions & 1 deletion app/scripts/lib/AccountIdentitiesPetnamesBridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ describe('AccountIdentitiesPetnamesBridge', () => {
});

describe('shouldSyncPetname', () => {
// @ts-expect-error This is missing from the Mocha type definitions
it.each([
{
origin: NameOrigin.ACCOUNT_IDENTITY,
Expand All @@ -216,7 +217,13 @@ describe('AccountIdentitiesPetnamesBridge', () => {
},
])(
'returns $expectedReturn if origin is $origin',
({ origin, expectedReturn }) => {
({
origin,
expectedReturn,
}: {
origin: NameOrigin;
expectedReturn: boolean;
}) => {
class TestBridge extends AccountIdentitiesPetnamesBridge {
public shouldSyncPetname(entry: PetnameEntry): boolean {
return super.shouldSyncPetname(entry);
Expand Down
4 changes: 3 additions & 1 deletion app/scripts/lib/keyring-snaps-permissions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ describe('keyringSnapPermissionsBuilder', () => {
expect(permissions()).toStrictEqual([]);
});

// @ts-expect-error This is missing from the Mocha type definitions
it.each([
'',
'null',
Expand All @@ -84,7 +85,7 @@ describe('keyringSnapPermissionsBuilder', () => {
1,
0,
-1,
])('"%s" cannot call any methods', (origin) => {
])('"%s" cannot call any methods', (origin: unknown) => {
const permissions = keyringSnapPermissionsBuilder(
mockController,
// TODO: Replace `any` with type
Expand All @@ -96,6 +97,7 @@ describe('keyringSnapPermissionsBuilder', () => {
});

describe('isProtocolAllowed', () => {
// @ts-expect-error This is missing from the Mocha type definitions
it.each([
['http://some-dapp.com', true],
['https://some-dapp.com', true],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ describe('createUnsupportedMethodMiddleware', () => {
expect(endMock).not.toHaveBeenCalled();
});

// @ts-expect-error This function is missing from the Mocha type definitions
it.each([...UNSUPPORTED_RPC_METHODS.keys()])(
'ends requests for methods that are on the list of unsupported methods: %s',
(method) => {
(method: string) => {
const middleware = createUnsupportedMethodMiddleware();
const nextMock = jest.fn();
const endMock = jest.fn();
Expand Down
1 change: 1 addition & 0 deletions app/scripts/lib/snap-keyring/utils/isBlockedUrl.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ describe('isBlockedUrl', () => {
},
});

// @ts-expect-error This is missing from the Mocha type definitions
it.each([
['http://metamask.io', false],
['https://metamask.io', false],
Expand Down
3 changes: 2 additions & 1 deletion app/scripts/migrations/095.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,12 +156,13 @@ describe('migration #95', () => {
});
});

// @ts-expect-error This is missing from the Mocha type definitions
it.each([
['undefined', undefined],
['empty', {}],
])(
'does nothing if incoming transactions %s',
async (_title, incomingTransactions) => {
async (_title: string, incomingTransactions: unknown) => {
const oldData = {
some: 'data',
IncomingTransactionsController: {
Expand Down
3 changes: 2 additions & 1 deletion test/data/confirmations/personal_sign.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export const PERSONAL_SIGN_SENDER_ADDRESS = '0x8eeee1781fd885ff5ddef7789486676961873d12';
export const PERSONAL_SIGN_SENDER_ADDRESS =
'0x8eeee1781fd885ff5ddef7789486676961873d12';

export const unapprovedPersonalSignMsg = {
id: '0050d5b0-c023-11ee-a0cb-3390a510a0ab',
Expand Down
2 changes: 1 addition & 1 deletion test/e2e/accounts/remove-account-snap.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { strict: assert } = require('assert');
import { strict as assert } from 'assert';
import { Suite } from 'mocha';
import FixtureBuilder from '../fixture-builder';
import { WINDOW_TITLES, defaultGanacheOptions, withFixtures } from '../helpers';
Expand Down
3 changes: 0 additions & 3 deletions test/e2e/flask/user-operations.spec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { TransactionParams } from '@metamask/transaction-controller';
import {
withFixtures,
unlockWallet,
openDapp,
switchToNotificationWindow,
DAPP_URL,
WINDOW_TITLES,
sendTransaction,
convertETHToHexGwei,
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/mmi/custodian-hooks/ICustodianTestClient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type BrowserContext } from '@playwright/test';

export interface ICustodianTestClient {
export type ICustodianTestClient = {
/** This method is expected to be used for initial test setup and to keep the context object in order to manage extra screen actions */
setup: (context?: BrowserContext) => Promise<void>;

Expand Down Expand Up @@ -36,4 +36,4 @@ export interface ICustodianTestClient {

/** This method should return the list of account titles to be selected when MMI custodian is connected */
getSelectedAccounts: () => Promise<string[]>;
}
};
26 changes: 20 additions & 6 deletions test/e2e/mmi/custodian-hooks/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ export class CustodianTestClient implements ICustodianTestClient {
const maxRetries = 3;
const retryInterval = 3000;
let retries = 0;
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let transaction: any;
while (retries < maxRetries) {
try {
Expand All @@ -154,7 +156,7 @@ export class CustodianTestClient implements ICustodianTestClient {
console.log(`Retrying in ${retryInterval / 1000} seconds...`);
await new Promise((resolve) => setTimeout(resolve, retryInterval));
} else {
throw error(
throw new Error(
`👎 Max retries (${maxRetries}) reached. Saturn tx not found.`,
);
}
Expand Down Expand Up @@ -193,6 +195,8 @@ export class CustodianTestClient implements ICustodianTestClient {
try {
const transactions = await this.getEIP721TransactionStatusCreated();
const { id } = transactions.find(
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(transaction: any) =>
transaction?.payload?.message?.contents === signedTransactionTime,
);
Expand Down Expand Up @@ -260,7 +264,7 @@ export class CustodianTestClient implements ICustodianTestClient {
const diffTime = transactions.map((tx: { createdAt: string }) =>
Math.abs(
new Date(tx.createdAt).getTime() -
parseInt(signedTransactionTime, 10),
parseInt(signedTransactionTime, 10),
),
);
const min = Math.min(...diffTime);
Expand Down Expand Up @@ -295,6 +299,8 @@ export class CustodianTestClient implements ICustodianTestClient {
return transactions[index];
}

// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async getPersonalSignatureTransactionStatusCreated(): Promise<any[]> {
const authorization = this.bearerToken;
return await axios
Expand All @@ -317,6 +323,8 @@ export class CustodianTestClient implements ICustodianTestClient {
});
}

// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async getEIP721TransactionStatusCreated(): Promise<any[]> {
const authorization = this.bearerToken;
return await axios
Expand Down Expand Up @@ -347,13 +355,19 @@ export class CustodianTestClient implements ICustodianTestClient {
return txId;
}

// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public async postConnectionRequest(data: any) {
return (await axios
.post("https://neptune-custody.dev.metamask-institutional.io/qrcode/connection-request", data, {
headers: {
'Content-Type': 'application/json',
.post(
'https://neptune-custody.dev.metamask-institutional.io/qrcode/connection-request',
data,
{
headers: {
'Content-Type': 'application/json',
},
},
})
)
.then(function (response) {
expect(response.status).toBe(200);
return response.data;
Expand Down
2 changes: 2 additions & 0 deletions test/e2e/mmi/helpers/custodian-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ export async function getCustodianInfoByName(name: string) {
// First get an admin token
try {
const { custodians } = (await axios.get(`${MMI_E2E_MMI_CONFIG_URL}`)).data;
// TODO: Replace `any` with type
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return custodians.filter(function (custodian: any) {
return custodian.name === name;
});
Expand Down
4 changes: 2 additions & 2 deletions test/e2e/mmi/helpers/dapps-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,6 @@ export async function callTestDappBtn(
);
return {
dummyDApp,
signedTransactionTime
}
signedTransactionTime,
};
}
Loading

0 comments on commit 63851c9

Please sign in to comment.