Skip to content

Commit

Permalink
fix: add unit test for assets polling loops (#28646)
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 goal of this PR is to add unit tests for all multichain assets
polling loops

<!--
Write a short description of the changes included in this pull request,
also include relevant motivation and context. Have in mind the following
questions:
1. What is the reason for the change?
2. What is the improvement/solution?
-->

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

## **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
Extension Coding
Standards](https://github.com/MetaMask/metamask-extension/blob/develop/.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-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
salimtb authored Nov 22, 2024
1 parent 89a06d2 commit b38244b
Show file tree
Hide file tree
Showing 4 changed files with 588 additions and 0 deletions.
143 changes: 143 additions & 0 deletions ui/hooks/useAccountTrackerPolling.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import { renderHookWithProvider } from '../../test/lib/render-helpers';
import {
accountTrackerStartPolling,
accountTrackerStopPollingByPollingToken,
} from '../store/actions';
import useAccountTrackerPolling from './useAccountTrackerPolling';

let mockPromises: Promise<string>[];

jest.mock('../store/actions', () => ({
accountTrackerStartPolling: jest.fn().mockImplementation((input) => {
const promise = Promise.resolve(`${input}_tracking`);
mockPromises.push(promise);
return promise;
}),
accountTrackerStopPollingByPollingToken: jest.fn(),
}));

let originalPortfolioView: string | undefined;

describe('useAccountTrackerPolling', () => {
beforeEach(() => {
// Mock process.env.PORTFOLIO_VIEW
originalPortfolioView = process.env.PORTFOLIO_VIEW;
process.env.PORTFOLIO_VIEW = 'true'; // Set your desired mock value here

mockPromises = [];
jest.clearAllMocks();
});

afterEach(() => {
// Restore the original value
process.env.PORTFOLIO_VIEW = originalPortfolioView;
});

it('should poll account trackers for network client IDs when enabled and stop on dismount', async () => {
process.env.PORTFOLIO_VIEW = 'true';

const state = {
metamask: {
isUnlocked: true,
completedOnboarding: true,
selectedNetworkClientId: 'selectedNetworkClientId',
networkConfigurationsByChainId: {
'0x1': {
chainId: '0x1',
defaultRpcEndpointIndex: 0,
rpcEndpoints: [
{
networkClientId: 'selectedNetworkClientId',
},
],
},
'0x89': {
chainId: '0x89',
defaultRpcEndpointIndex: 0,
rpcEndpoints: [
{
networkClientId: 'selectedNetworkClientId2',
},
],
},
},
},
};

const { unmount } = renderHookWithProvider(
() => useAccountTrackerPolling(),
state,
);

// Should poll each client ID
await Promise.all(mockPromises);
expect(accountTrackerStartPolling).toHaveBeenCalledTimes(2);
expect(accountTrackerStartPolling).toHaveBeenCalledWith(
'selectedNetworkClientId',
);
expect(accountTrackerStartPolling).toHaveBeenCalledWith(
'selectedNetworkClientId2',
);

// Stop polling on dismount
unmount();
expect(accountTrackerStopPollingByPollingToken).toHaveBeenCalledTimes(2);
expect(accountTrackerStopPollingByPollingToken).toHaveBeenCalledWith(
'selectedNetworkClientId_tracking',
);
});

it('should not poll if onboarding is not completed', async () => {
const state = {
metamask: {
isUnlocked: true,
completedOnboarding: false,
networkConfigurationsByChainId: {
'0x1': {},
},
},
};

renderHookWithProvider(() => useAccountTrackerPolling(), state);

await Promise.all(mockPromises);
expect(accountTrackerStartPolling).toHaveBeenCalledTimes(0);
expect(accountTrackerStopPollingByPollingToken).toHaveBeenCalledTimes(0);
});

it('should not poll when locked', async () => {
const state = {
metamask: {
isUnlocked: false,
completedOnboarding: true,
networkConfigurationsByChainId: {
'0x1': {},
},
},
};

renderHookWithProvider(() => useAccountTrackerPolling(), state);

await Promise.all(mockPromises);
expect(accountTrackerStartPolling).toHaveBeenCalledTimes(0);
expect(accountTrackerStopPollingByPollingToken).toHaveBeenCalledTimes(0);
});

it('should not poll when no network client IDs are provided', async () => {
const state = {
metamask: {
isUnlocked: true,
completedOnboarding: true,
networkConfigurationsByChainId: {
'0x1': {},
},
},
};

renderHookWithProvider(() => useAccountTrackerPolling(), state);

await Promise.all(mockPromises);
expect(accountTrackerStartPolling).toHaveBeenCalledTimes(0);
expect(accountTrackerStopPollingByPollingToken).toHaveBeenCalledTimes(0);
});
});
128 changes: 128 additions & 0 deletions ui/hooks/useCurrencyRatePolling.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import { renderHookWithProvider } from '../../test/lib/render-helpers';
import {
currencyRateStartPolling,
currencyRateStopPollingByPollingToken,
} from '../store/actions';
import useCurrencyRatePolling from './useCurrencyRatePolling';

let mockPromises: Promise<string>[];

jest.mock('../store/actions', () => ({
currencyRateStartPolling: jest.fn().mockImplementation((input) => {
const promise = Promise.resolve(`${input}_rates`);
mockPromises.push(promise);
return promise;
}),
currencyRateStopPollingByPollingToken: jest.fn(),
}));

describe('useCurrencyRatePolling', () => {
beforeEach(() => {
mockPromises = [];
jest.clearAllMocks();
});

it('should poll currency rates for native currencies when enabled and stop on dismount', async () => {
const state = {
metamask: {
isUnlocked: true,
completedOnboarding: true,
useCurrencyRateCheck: true,
selectedNetworkClientId: 'selectedNetworkClientId',
networkConfigurationsByChainId: {
'0x1': {
nativeCurrency: 'ETH',
defaultRpcEndpointIndex: 0,
rpcEndpoints: [
{
networkClientId: 'selectedNetworkClientId',
},
],
},
'0x89': {
nativeCurrency: 'BNB',
defaultRpcEndpointIndex: 0,
rpcEndpoints: [
{
networkClientId: 'selectedNetworkClientId2',
},
],
},
},
},
};

const { unmount } = renderHookWithProvider(
() => useCurrencyRatePolling(),
state,
);

await Promise.all(mockPromises);
expect(currencyRateStartPolling).toHaveBeenCalledTimes(1);
expect(currencyRateStartPolling).toHaveBeenCalledWith(['ETH', 'BNB']);

// Stop polling on dismount
unmount();
expect(currencyRateStopPollingByPollingToken).toHaveBeenCalledTimes(1);
expect(currencyRateStopPollingByPollingToken).toHaveBeenCalledWith(
'ETH,BNB_rates',
);
});

it('should not poll if onboarding is not completed', async () => {
const state = {
metamask: {
isUnlocked: true,
completedOnboarding: false,
useCurrencyRateCheck: true,
networkConfigurationsByChainId: {
'0x1': { nativeCurrency: 'ETH' },
},
},
};

renderHookWithProvider(() => useCurrencyRatePolling(), state);

await Promise.all(mockPromises);
expect(currencyRateStartPolling).toHaveBeenCalledTimes(0);
expect(currencyRateStopPollingByPollingToken).toHaveBeenCalledTimes(0);
});

it('should not poll when locked', async () => {
const state = {
metamask: {
isUnlocked: false,
completedOnboarding: true,
useCurrencyRateCheck: true,
networkConfigurationsByChainId: {
'0x1': { nativeCurrency: 'ETH' },
},
},
};

renderHookWithProvider(() => useCurrencyRatePolling(), state);

await Promise.all(mockPromises);
expect(currencyRateStartPolling).toHaveBeenCalledTimes(0);
expect(currencyRateStopPollingByPollingToken).toHaveBeenCalledTimes(0);
});

it('should not poll when currency rate checking is disabled', async () => {
const state = {
metamask: {
isUnlocked: true,
completedOnboarding: true,
useCurrencyRateCheck: false,
networkConfigurationsByChainId: {
'0x1': { nativeCurrency: 'ETH' },
},
},
};

renderHookWithProvider(() => useCurrencyRatePolling(), state);

await Promise.all(mockPromises);
expect(currencyRateStartPolling).toHaveBeenCalledTimes(0);
expect(currencyRateStopPollingByPollingToken).toHaveBeenCalledTimes(0);
});
});
Loading

0 comments on commit b38244b

Please sign in to comment.