diff --git a/packages/page-accounts/src/Accounts/Account.tsx b/packages/page-accounts/src/Accounts/Account.tsx index 7772ef565c..6294274a89 100644 --- a/packages/page-accounts/src/Accounts/Account.tsx +++ b/packages/page-accounts/src/Accounts/Account.tsx @@ -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(api.api.derive.balances?.all, [address]); + const balancesAll = useBalancesAll(address); const democracyLocks = useCall(api.api.derive.democracy?.locks, [address]); const recoveryInfo = useCall(api.api.query.recovery?.recoverable, [address], transformRecovery); const multiInfos = useMultisigApprovals(address); @@ -584,6 +584,7 @@ function Account ({ account: { address, meta }, className = '', delegation, filt { + 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); + }; +}); diff --git a/packages/page-accounts/test/hooks/default.ts b/packages/page-accounts/test/hooks/default.ts new file mode 100644 index 0000000000..676f0b42a3 --- /dev/null +++ b/packages/page-accounts/test/hooks/default.ts @@ -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(); diff --git a/packages/page-accounts/test/pages/accountsPage.tsx b/packages/page-accounts/test/pages/accountsPage.tsx new file mode 100644 index 0000000000..1ed85abc51 --- /dev/null +++ b/packages/page-accounts/test/pages/accountsPage.tsx @@ -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( + <> +
+ + + + + + + + + + + + + ); + } + + async findAccountsTable (): Promise { + this.assertRendered(); + + return await screen.findByRole('table'); + } + + async findAccountRows (): Promise { + 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(); + } + } +} diff --git a/packages/react-hooks/src/index.ts b/packages/react-hooks/src/index.ts index 69fddf0cfd..fc741fe08e 100644 --- a/packages/react-hooks/src/index.ts +++ b/packages/react-hooks/src/index.ts @@ -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'; diff --git a/packages/react-hooks/src/useAccounts.ts b/packages/react-hooks/src/useAccounts.ts index ca277b84d0..2f564bedc2 100644 --- a/packages/react-hooks/src/useAccounts.ts +++ b/packages/react-hooks/src/useAccounts.ts @@ -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 diff --git a/packages/react-hooks/src/useBalancesAll.ts b/packages/react-hooks/src/useBalancesAll.ts new file mode 100644 index 0000000000..8b69ec2b68 --- /dev/null +++ b/packages/react-hooks/src/useBalancesAll.ts @@ -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(api.derive.balances?.all, [accountAddress]); +} diff --git a/packages/react-hooks/src/useStakingInfo.ts b/packages/react-hooks/src/useStakingInfo.ts new file mode 100644 index 0000000000..38d5a63fe7 --- /dev/null +++ b/packages/react-hooks/src/useStakingInfo.ts @@ -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(api.derive.staking?.account, [accountId]); +} diff --git a/packages/react-query/src/FormatBalance.tsx b/packages/react-query/src/FormatBalance.tsx index e149d71845..dda94c0322 100644 --- a/packages/react-query/src/FormatBalance.tsx +++ b/packages/react-query/src/FormatBalance.tsx @@ -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 (
- {label ? <>{label}  : ''}{ - valueFormatted - ? splitFormat(valueFormatted, labelPost, isShort) - : value - ? value === 'all' - ? t('everything{{labelPost}}', { replace: { labelPost } }) - : applyFormat(value, formatInfo, withCurrency, withSi, isShort, labelPost) - : `-${labelPost || ''}` - }{children} + {label ? <>{label}  : ''} + { + valueFormatted + ? splitFormat(valueFormatted, labelPost, isShort) + : value + ? value === 'all' + ? t('everything{{labelPost}}', { replace: { labelPost } }) + : applyFormat(value, formatInfo, withCurrency, withSi, isShort, labelPost) + : `-${labelPost || ''}` + }{children}
); } diff --git a/packages/test-support/src/creation/balance.ts b/packages/test-support/src/creation/balance.ts index fa5af3cd34..8d1b50fcb4 100644 --- a/packages/test-support/src/creation/balance.ts +++ b/packages/test-support/src/creation/balance.ts @@ -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)); }