Add app-accounts testing support (#5872)
This commit is contained in:
parent
c28c6cc121
commit
809520ddc0
@ -3,7 +3,7 @@
|
||||
|
||||
import type BN from 'bn.js';
|
||||
import type { SubmittableExtrinsic } from '@polkadot/api/types';
|
||||
import type { DeriveBalancesAll, DeriveDemocracyLock } from '@polkadot/api-derive/types';
|
||||
import type { DeriveDemocracyLock } from '@polkadot/api-derive/types';
|
||||
import type { Ledger } from '@polkadot/hw-ledger';
|
||||
import type { ActionStatus } from '@polkadot/react-components/Status/types';
|
||||
import type { ThemeDef } from '@polkadot/react-components/types';
|
||||
@ -17,7 +17,7 @@ import styled, { ThemeContext } from 'styled-components';
|
||||
|
||||
import { ApiPromise } from '@polkadot/api';
|
||||
import { AddressInfo, AddressMini, AddressSmall, Badge, Button, ChainLock, CryptoType, Forget, Icon, IdentityIcon, LinkExternal, Menu, Popup, StatusContext, Tags } from '@polkadot/react-components';
|
||||
import { useAccountInfo, useApi, useBestNumber, useCall, useLedger, useToggle } from '@polkadot/react-hooks';
|
||||
import { useAccountInfo, useApi, useBalancesAll, useBestNumber, useCall, useLedger, useToggle } from '@polkadot/react-hooks';
|
||||
import { keyring } from '@polkadot/ui-keyring';
|
||||
import { BN_ZERO, formatBalance, formatNumber, isFunction } from '@polkadot/util';
|
||||
|
||||
@ -93,7 +93,7 @@ function Account ({ account: { address, meta }, className = '', delegation, filt
|
||||
const api = useApi();
|
||||
const { getLedger } = useLedger();
|
||||
const bestNumber = useBestNumber();
|
||||
const balancesAll = useCall<DeriveBalancesAll>(api.api.derive.balances?.all, [address]);
|
||||
const balancesAll = useBalancesAll(address);
|
||||
const democracyLocks = useCall<DeriveDemocracyLock[]>(api.api.derive.democracy?.locks, [address]);
|
||||
const recoveryInfo = useCall<RecoveryConfig | null>(api.api.query.recovery?.recoverable, [address], transformRecovery);
|
||||
const multiInfos = useMultisigApprovals(address);
|
||||
@ -584,6 +584,7 @@ function Account ({ account: { address, meta }, className = '', delegation, filt
|
||||
<td className='number'>
|
||||
<AddressInfo
|
||||
address={address}
|
||||
balancesAll={balancesAll}
|
||||
withBalance
|
||||
withBalanceToggle
|
||||
withExtended={false}
|
||||
|
||||
118
packages/page-accounts/src/Accounts/index.spec.ts
Normal file
118
packages/page-accounts/src/Accounts/index.spec.ts
Normal file
@ -0,0 +1,118 @@
|
||||
// Copyright 2017-2021 @polkadot/page-accounts authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { Balance } from '@polkadot/types/interfaces';
|
||||
|
||||
import { within } from '@testing-library/react';
|
||||
|
||||
import i18next from '@polkadot/react-components/i18n';
|
||||
import { balanceOf } from '@polkadot/test-support/creation/balance';
|
||||
import { MemoryStore } from '@polkadot/test-support/keyring';
|
||||
import { keyring } from '@polkadot/ui-keyring';
|
||||
|
||||
import { AccountsPage } from '../../test/pages/accountsPage';
|
||||
|
||||
describe('Accounts page', () => {
|
||||
let accountsPage: AccountsPage;
|
||||
|
||||
beforeAll(async () => {
|
||||
await i18next.changeLanguage('en');
|
||||
keyring.loadAll({ isDevelopment: true, store: new MemoryStore() });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
accountsPage = new AccountsPage();
|
||||
});
|
||||
|
||||
describe('when no accounts', () => {
|
||||
it('shows a table', async () => {
|
||||
accountsPage.renderPage([]);
|
||||
|
||||
const accountsTable = await accountsPage.findAccountsTable();
|
||||
|
||||
expect(accountsTable).not.toBeNull();
|
||||
});
|
||||
|
||||
it('the accounts table contains no account rows', async () => {
|
||||
accountsPage.renderPage([]);
|
||||
|
||||
const accountRows = await accountsPage.findAccountRows();
|
||||
|
||||
expect(accountRows).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('the accounts table contains a message about no accounts available', async () => {
|
||||
accountsPage.renderPage([]);
|
||||
|
||||
const accountsTable = await accountsPage.findAccountsTable();
|
||||
const noAccountsMessage = await within(accountsTable).findByText(
|
||||
'You don\'t have any accounts. Some features are currently hidden and will only become available once you have accounts.');
|
||||
|
||||
expect(noAccountsMessage).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('when some accounts exist', () => {
|
||||
it('the accounts table contains some account rows', async () => {
|
||||
accountsPage.renderPage([
|
||||
{
|
||||
address: '5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy',
|
||||
balance: {
|
||||
freeBalance: balance(10000)
|
||||
}
|
||||
},
|
||||
{
|
||||
address: '5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw',
|
||||
balance: {
|
||||
freeBalance: balance(999)
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
const accountRows = await accountsPage.findAccountRows();
|
||||
|
||||
expect(accountRows).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('account rows display the total balance info', async () => {
|
||||
accountsPage.renderPage([
|
||||
{
|
||||
address: '5DAAnrj7VHTznn2AWBemMuyBwZWs6FNFjdyVXUeYum3PTXFy',
|
||||
balance: {
|
||||
freeBalance: balance(500)
|
||||
}
|
||||
},
|
||||
{
|
||||
address: '5HGjWAeFDfFCWPsjFQdVV2Msvz2XtMktvgocEZcCj68kUMaw',
|
||||
balance: {
|
||||
freeBalance: balance(200),
|
||||
reservedBalance: balance(150)
|
||||
}
|
||||
}
|
||||
]);
|
||||
const rows = await accountsPage.findAccountRows();
|
||||
|
||||
const row1TotalActual = await within(rows[0]).findByTestId('balance-summary');
|
||||
const row1TotalExpected = accountsPage.format(balance(500));
|
||||
|
||||
expect(row1TotalActual).toHaveTextContent(row1TotalExpected);
|
||||
|
||||
const row2TotalActual = await within(rows[1]).findByTestId('balance-summary');
|
||||
const row2TotalExpected = accountsPage.format(balance(350));
|
||||
|
||||
expect(row2TotalActual).toHaveTextContent(row2TotalExpected);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Creates a balance instance for testing purposes which most often do not need to specifiy/use decimal part.
|
||||
* @param amountInt Integer part of the balance number
|
||||
* @param decimalsString Decimals part of the balance number. Note! This is a string sequence just after '.' separator
|
||||
* that is the point that separates integers from decimals. E.g. (100, 4567) => 100.45670000...00
|
||||
*/
|
||||
const balance = function (amountInt: number, decimalsString?: string): Balance {
|
||||
const decimalsPadded = (decimalsString || '').padEnd(12, '0');
|
||||
|
||||
return balanceOf(amountInt.toString() + decimalsPadded);
|
||||
};
|
||||
});
|
||||
118
packages/page-accounts/test/hooks/default.ts
Normal file
118
packages/page-accounts/test/hooks/default.ts
Normal file
@ -0,0 +1,118 @@
|
||||
// Copyright 2017-2021 @polkadot/page-accounts authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { DeriveBalancesAll, DeriveStakingAccount } from '@polkadot/api-derive/types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
import { UseAccounts } from '@polkadot/react-hooks/useAccounts';
|
||||
import { balanceOf } from '@polkadot/test-support/creation/balance';
|
||||
|
||||
export interface Account {
|
||||
balance: DeriveBalancesAll,
|
||||
staking: DeriveStakingAccount
|
||||
}
|
||||
|
||||
export type AccountsMap = { [address: string]: Account };
|
||||
|
||||
/**
|
||||
* Test inputs structure
|
||||
*/
|
||||
export interface AccountOverrides {
|
||||
address: string;
|
||||
|
||||
balance?: {
|
||||
[P in keyof DeriveBalancesAll]?: DeriveBalancesAll[P];
|
||||
};
|
||||
staking?: {
|
||||
[P in keyof DeriveStakingAccount]?: DeriveStakingAccount[P];
|
||||
};
|
||||
}
|
||||
|
||||
export const emptyAccounts: UseAccounts = {
|
||||
allAccounts: [],
|
||||
allAccountsHex: [],
|
||||
areAccountsLoaded: true,
|
||||
hasAccounts: false,
|
||||
isAccount: () => true
|
||||
};
|
||||
|
||||
// here it's extremely hard to reconstruct the entire DeriveBalancesAll upfront, so we incrementally add properties
|
||||
// instead along the way; thus the need to tell the tsc we know what we are doing here
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
export const defaultBalanceAccount: DeriveBalancesAll = {
|
||||
accountNonce: new BN(1),
|
||||
additional: [],
|
||||
availableBalance: balanceOf(0),
|
||||
freeBalance: balanceOf(0),
|
||||
lockedBalance: balanceOf(0),
|
||||
lockedBreakdown: [],
|
||||
reservedBalance: balanceOf(0)
|
||||
} as any;
|
||||
|
||||
// here it's extremely hard to reconstruct the entire DeriveStakingAccount upfront,
|
||||
// so we set just the properties that we use in page-accounts
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
export const defaultStakingAccount: DeriveStakingAccount = {
|
||||
nextSessionIds: [],
|
||||
nominators: [],
|
||||
redeemable: balanceOf(0),
|
||||
sessionIds: [],
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
stakingLedger: {
|
||||
active: {
|
||||
unwrap: () => new BN(0)
|
||||
}
|
||||
} as any,
|
||||
unlocking: [
|
||||
{
|
||||
remainingEras: new BN('1000000000'),
|
||||
value: balanceOf(0)
|
||||
},
|
||||
{
|
||||
remainingEras: new BN('2000000000'),
|
||||
value: balanceOf(0)
|
||||
},
|
||||
{
|
||||
remainingEras: new BN('3000000000'),
|
||||
value: balanceOf(0)
|
||||
}
|
||||
]
|
||||
} as any;
|
||||
|
||||
class MockAccountHooks {
|
||||
public useAccounts: UseAccounts = emptyAccounts;
|
||||
public accountsMap: AccountsMap = {};
|
||||
|
||||
public nonce: BN = new BN(1);
|
||||
|
||||
public setAccounts (accounts: AccountOverrides[]): void {
|
||||
this.useAccounts = {
|
||||
allAccounts: accounts.map((account) => account.address),
|
||||
allAccountsHex: [],
|
||||
areAccountsLoaded: true,
|
||||
hasAccounts: accounts && accounts.length !== 0,
|
||||
isAccount: () => true
|
||||
};
|
||||
|
||||
for (const account of accounts) {
|
||||
const staking = { ...defaultStakingAccount };
|
||||
const balance = { ...defaultBalanceAccount };
|
||||
|
||||
// Typescript does not recognize that keys and values from Object.entries are safe,
|
||||
// so we have to use "any" here.
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
|
||||
Object.entries(account.balance || balance).forEach(function ([key, value]) { (balance as any)[key] = value; });
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
|
||||
Object.entries(account.staking || staking).forEach(function ([key, value]) { (staking as any)[key] = value; });
|
||||
|
||||
this.accountsMap[account.address] = {
|
||||
balance: balance,
|
||||
staking: staking
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const mockAccountHooks = new MockAccountHooks();
|
||||
133
packages/page-accounts/test/pages/accountsPage.tsx
Normal file
133
packages/page-accounts/test/pages/accountsPage.tsx
Normal file
@ -0,0 +1,133 @@
|
||||
// Copyright 2017-2021 @polkadot/page-accounts authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { render, RenderResult, screen, within } from '@testing-library/react';
|
||||
import BN from 'bn.js';
|
||||
import React, { Suspense } from 'react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { ThemeProvider } from 'styled-components';
|
||||
|
||||
import { lightTheme } from '@polkadot/apps/themes';
|
||||
import { POLKADOT_GENESIS } from '@polkadot/apps-config';
|
||||
import { ApiContext } from '@polkadot/react-api';
|
||||
import { ApiProps } from '@polkadot/react-api/types';
|
||||
import { QueueProvider } from '@polkadot/react-components/Status/Context';
|
||||
import { PartialQueueTxExtrinsic, QueueProps, QueueTxExtrinsicAdd } from '@polkadot/react-components/Status/types';
|
||||
import { TypeRegistry } from '@polkadot/types/create';
|
||||
import { Balance, BlockNumber } from '@polkadot/types/interfaces';
|
||||
import { formatBalance } from '@polkadot/util';
|
||||
|
||||
import { AccountOverrides, mockAccountHooks } from '../hooks/default';
|
||||
import Overview from '../pages/../../src/Accounts/index';
|
||||
|
||||
let queueExtrinsic: (value: PartialQueueTxExtrinsic) => void;
|
||||
|
||||
class NotYetRendered extends Error {
|
||||
}
|
||||
|
||||
export type AccountRow = HTMLElement;
|
||||
|
||||
jest.mock('@polkadot/react-hooks/useAccounts', () => ({
|
||||
useAccounts: () => mockAccountHooks.useAccounts
|
||||
}));
|
||||
|
||||
jest.mock('@polkadot/react-hooks/useLoadingDelay', () => ({
|
||||
useLoadingDelay: () => false
|
||||
}));
|
||||
|
||||
jest.mock('@polkadot/react-hooks/useBalancesAll', () => ({
|
||||
useBalancesAll: (address: string) => mockAccountHooks.accountsMap[address].balance
|
||||
}));
|
||||
|
||||
jest.mock('@polkadot/react-hooks/useStakingInfo', () => ({
|
||||
useStakingInfo: (address: string) => mockAccountHooks.accountsMap[address].staking
|
||||
}));
|
||||
|
||||
jest.mock('@polkadot/react-hooks/useBestNumber', () => ({
|
||||
useBestNumber: () => 1
|
||||
}));
|
||||
|
||||
export class AccountsPage {
|
||||
private renderResult?: RenderResult
|
||||
|
||||
renderPage (accounts: AccountOverrides[]): void {
|
||||
mockAccountHooks.setAccounts(accounts);
|
||||
const mockApi: ApiProps = {
|
||||
api: {
|
||||
derive: {
|
||||
accounts: {
|
||||
info: () => Promise.resolve(() => { /**/
|
||||
})
|
||||
},
|
||||
balances: {
|
||||
all: () => ({
|
||||
accountNonce: mockAccountHooks.nonce,
|
||||
additional: [],
|
||||
freeBalance: 0,
|
||||
lockedBreakdown: [],
|
||||
reservedBalance: 0
|
||||
})
|
||||
},
|
||||
chain: {
|
||||
bestNumber: () => new BN(1) as BlockNumber
|
||||
}
|
||||
},
|
||||
genesisHash: new TypeRegistry().createType('Hash', POLKADOT_GENESIS),
|
||||
query: {},
|
||||
registry: { chainDecimals: [12], chainTokens: ['Unit'] },
|
||||
tx: {
|
||||
council: {
|
||||
}
|
||||
}
|
||||
},
|
||||
systemName: 'substrate'
|
||||
} as unknown as ApiProps;
|
||||
|
||||
queueExtrinsic = jest.fn() as QueueTxExtrinsicAdd;
|
||||
const queue = {
|
||||
queueExtrinsic
|
||||
} as QueueProps;
|
||||
|
||||
this.renderResult = render(
|
||||
<>
|
||||
<div id='tooltips'/>
|
||||
<Suspense fallback='...'>
|
||||
<QueueProvider value={queue}>
|
||||
<MemoryRouter>
|
||||
<ThemeProvider theme={lightTheme}>
|
||||
<ApiContext.Provider value={mockApi}>
|
||||
<Overview/>
|
||||
</ApiContext.Provider>
|
||||
</ThemeProvider>
|
||||
</MemoryRouter>
|
||||
</QueueProvider>
|
||||
</Suspense>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
async findAccountsTable (): Promise<HTMLElement> {
|
||||
this.assertRendered();
|
||||
|
||||
return await screen.findByRole('table');
|
||||
}
|
||||
|
||||
async findAccountRows (): Promise<AccountRow[]> {
|
||||
this.assertRendered();
|
||||
const table = await this.findAccountsTable();
|
||||
const tableBody = table.getElementsByTagName('tbody')[0];
|
||||
const rows = await within(tableBody).findAllByRole('row');
|
||||
|
||||
return rows.filter((r) => r.className.startsWith('Account-'));
|
||||
}
|
||||
|
||||
format (amount: Balance): string {
|
||||
return formatBalance(amount, { decimals: 12, withUnit: true });
|
||||
}
|
||||
|
||||
private assertRendered () {
|
||||
if (this.renderResult === undefined) {
|
||||
throw new NotYetRendered();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -8,6 +8,7 @@ export { useAddresses } from './useAddresses';
|
||||
export { useApi } from './useApi';
|
||||
export { useApiUrl } from './useApiUrl';
|
||||
export { useAvailableSlashes } from './useAvailableSlashes';
|
||||
export { useBalancesAll } from './useBalancesAll';
|
||||
export { useBestHash } from './useBestHash';
|
||||
export { useBestNumber } from './useBestNumber';
|
||||
export { useBlockTime } from './useBlockTime';
|
||||
|
||||
@ -9,7 +9,7 @@ import { decodeAddress } from '@polkadot/util-crypto';
|
||||
|
||||
import { useIsMountedRef } from './useIsMountedRef';
|
||||
|
||||
interface UseAccounts {
|
||||
export interface UseAccounts {
|
||||
allAccounts: string[];
|
||||
allAccountsHex: string[];
|
||||
areAccountsLoaded: boolean
|
||||
|
||||
19
packages/react-hooks/src/useBalancesAll.ts
Normal file
19
packages/react-hooks/src/useBalancesAll.ts
Normal file
@ -0,0 +1,19 @@
|
||||
// Copyright 2017-2021 @polkadot/react-hooks authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { DeriveBalancesAll } from '@polkadot/api-derive/types';
|
||||
|
||||
import { useApi } from './useApi';
|
||||
import { useCall } from './useCall';
|
||||
|
||||
/**
|
||||
* Gets the account full balance information
|
||||
*
|
||||
* @param accountAddress The account address of which balance is to be returned
|
||||
* @returns full information about account's balances
|
||||
*/
|
||||
export function useBalancesAll (accountAddress: string): DeriveBalancesAll | undefined {
|
||||
const { api } = useApi();
|
||||
|
||||
return useCall<DeriveBalancesAll>(api.derive.balances?.all, [accountAddress]);
|
||||
}
|
||||
12
packages/react-hooks/src/useStakingInfo.ts
Normal file
12
packages/react-hooks/src/useStakingInfo.ts
Normal file
@ -0,0 +1,12 @@
|
||||
// Copyright 2017-2021 @polkadot/app-bounties authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type { DeriveStakingAccount } from '@polkadot/api-derive/types';
|
||||
|
||||
import { useApi, useCall } from '@polkadot/react-hooks';
|
||||
|
||||
export function useStakingInfo (accountId: string | null): DeriveStakingAccount | undefined {
|
||||
const { api } = useApi();
|
||||
|
||||
return useCall<DeriveStakingAccount>(api.derive.staking?.account, [accountId]);
|
||||
}
|
||||
@ -84,15 +84,18 @@ function FormatBalance ({ children, className = '', format, formatIndex, isShort
|
||||
// labelPost here looks messy, however we ensure we have one less text node
|
||||
return (
|
||||
<div className={`ui--FormatBalance ${className}`}>
|
||||
{label ? <>{label} </> : ''}<span className='ui--FormatBalance-value'>{
|
||||
valueFormatted
|
||||
? splitFormat(valueFormatted, labelPost, isShort)
|
||||
: value
|
||||
? value === 'all'
|
||||
? t<string>('everything{{labelPost}}', { replace: { labelPost } })
|
||||
: applyFormat(value, formatInfo, withCurrency, withSi, isShort, labelPost)
|
||||
: `-${labelPost || ''}`
|
||||
}</span>{children}
|
||||
{label ? <>{label} </> : ''}
|
||||
<span
|
||||
className='ui--FormatBalance-value'
|
||||
data-testid='balance-summary'>{
|
||||
valueFormatted
|
||||
? splitFormat(valueFormatted, labelPost, isShort)
|
||||
: value
|
||||
? value === 'all'
|
||||
? t<string>('everything{{labelPost}}', { replace: { labelPost } })
|
||||
: applyFormat(value, formatInfo, withCurrency, withSi, isShort, labelPost)
|
||||
: `-${labelPost || ''}`
|
||||
}</span>{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -7,6 +7,6 @@ import BN from 'bn.js';
|
||||
|
||||
import { TypeRegistry } from '@polkadot/types/create';
|
||||
|
||||
export function balanceOf (number: number): Balance {
|
||||
export function balanceOf (number: number | string): Balance {
|
||||
return new TypeRegistry().createType('Balance', new BN(number));
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user