From d131d626659580f72cb71365c73410e118558342 Mon Sep 17 00:00:00 2001 From: Krzysztof Jelski Date: Mon, 11 Jan 2021 10:15:01 +0100 Subject: [PATCH] Add a fast UI test for bounties. (#4302) --- packages/page-bounties/src/Bounties.spec.tsx | 151 ++++++++++++++++++ packages/page-bounties/src/Bounties.tsx | 15 +- packages/page-bounties/src/BountyCreate.tsx | 43 ++--- .../src/BountyInitiateVoting.tsx | 8 +- packages/page-bounties/src/Summary.tsx | 10 +- .../src/helpers/calculateBountyBond.ts | 6 +- packages/page-bounties/src/hooks/index.ts | 5 + .../page-bounties/src/hooks/useBalance.ts | 13 ++ .../page-bounties/src/hooks/useBounties.tsx | 51 ++++++ 9 files changed, 250 insertions(+), 52 deletions(-) create mode 100644 packages/page-bounties/src/Bounties.spec.tsx create mode 100644 packages/page-bounties/src/hooks/index.ts create mode 100644 packages/page-bounties/src/hooks/useBalance.ts create mode 100644 packages/page-bounties/src/hooks/useBounties.tsx diff --git a/packages/page-bounties/src/Bounties.spec.tsx b/packages/page-bounties/src/Bounties.spec.tsx new file mode 100644 index 0000000000..0a4f6723f2 --- /dev/null +++ b/packages/page-bounties/src/Bounties.spec.tsx @@ -0,0 +1,151 @@ +// Copyright 2017-2021 @polkadot/app-bounties authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +import type { DeriveBounties } from '@polkadot/api-derive/types'; +import type { BlockNumber, Bounty, BountyIndex } from '@polkadot/types/interfaces'; + +import { fireEvent, render } 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 i18next from '@polkadot/react-components/i18n'; +import { TypeRegistry } from '@polkadot/types/create'; + +import Bounties from './Bounties'; +import { BountyApi } from './hooks'; + +function aBounty (): Bounty { + return new TypeRegistry().createType('Bounty'); +} + +function anIndex (): BountyIndex { + return new TypeRegistry().createType('BountyIndex'); +} + +function balanceOf (number: number) { + return new TypeRegistry().createType('Balance', new BN(number)); +} + +function aGenesisHash () { + return new TypeRegistry().createType('Hash', POLKADOT_GENESIS); +} + +let mockBountyApi: BountyApi = { + approveBounty: jest.fn(), + bestNumber: new BN(1) as BlockNumber, + bounties: [] as DeriveBounties, + bountyDepositBase: new BN(1), + bountyValueMinimum: new BN(1), + closeBounty: jest.fn(), + dataDepositPerByte: new BN(1), + maximumReasonLength: 100, + proposeBounty: jest.fn() +}; + +let mockBalance = balanceOf(1); + +const mockTreasury = { + burn: new BN(1), + spendPeriod: new BN(0), + value: balanceOf(1) +}; + +jest.mock('./hooks', () => { + return { + useBalance: () => mockBalance, + useBounties: () => mockBountyApi + }; +}); + +jest.mock('@polkadot/react-hooks/useTreasury', () => { + return { + useTreasury: () => mockTreasury + }; +}); + +describe('Bounties', () => { + beforeAll(async () => { + await i18next.changeLanguage('en'); + }); + + const renderBounties = (bountyApi: Partial = {}, { balance = 1 } = {}) => { + mockBountyApi = { ...mockBountyApi, ...bountyApi }; + mockBalance = balanceOf(balance); + const mockApi: ApiProps = { api: { + derive: { + accounts: { info: () => Promise.resolve(() => { /**/ }) } + }, + genesisHash: aGenesisHash(), + query: {}, + registry: { chainDecimals: 12 } + }, + systemName: 'substrate' } as unknown as ApiProps; + + return render( + + + + + + + + + + ); + }; + + it('shows empty list when no bounties', async () => { + const { findByText } = renderBounties(); + + expect(await findByText('No open bounties')).toBeTruthy(); + }); + + it('renders a bounty', async () => { + const { findByText, queryAllByText } = renderBounties({ bounties: [{ bounty: aBounty(), description: 'kusama comic book', index: anIndex(), proposals: [] }] }); + + expect(await findByText('kusama comic book')).toBeTruthy(); + expect(queryAllByText('No open bounties')).toHaveLength(0); + }); + + describe('create bounty modal', () => { + it('validates bounty length', async () => { + const { findByTestId, findByText } = renderBounties({ maximumReasonLength: 5 }); + + const addBountyButton = await findByText('Add Bounty'); + + fireEvent.click(addBountyButton); + + const titleInput = await findByTestId('bounty title'); + + fireEvent.change(titleInput, { target: { value: 'longer than 5' } }); + + expect(await findByText('Title too long')).toBeTruthy(); + }); + + it('validates balance is enough for bond', async () => { + const { findByTestId, findByText, queryByText } = renderBounties( + { bountyDepositBase: new BN(10), dataDepositPerByte: new BN(1) }, + { balance: 10 } + ); + + const addBountyButton = await findByText('Add Bounty'); + + fireEvent.click(addBountyButton); + expect(await findByText('Description of the Bounty (to be stored on-chain)')).toBeTruthy(); // wait for load + + expect(queryByText('Account does not have enough funds.')).toBeFalsy(); + + const titleInput = await findByTestId('bounty title'); + + fireEvent.change(titleInput, { target: { value: 'add bytes' } }); + + expect(await findByText('Account does not have enough funds.')).toBeTruthy(); + }); + }); +}); diff --git a/packages/page-bounties/src/Bounties.tsx b/packages/page-bounties/src/Bounties.tsx index e0df29c548..4e38855bac 100644 --- a/packages/page-bounties/src/Bounties.tsx +++ b/packages/page-bounties/src/Bounties.tsx @@ -1,24 +1,19 @@ // Copyright 2017-2021 @polkadot/app-bounties authors & contributors // SPDX-License-Identifier: Apache-2.0 -import type { DeriveBounties } from '@polkadot/api-derive/types'; -import type { BlockNumber } from '@polkadot/types/interfaces'; - import React, { useRef } from 'react'; import Summary from '@polkadot/app-bounties/Summary'; import { Button, Table } from '@polkadot/react-components'; -import { useApi, useCall } from '@polkadot/react-hooks'; import Bounty from './Bounty'; import BountyCreate from './BountyCreate'; +import { useBounties } from './hooks'; import { useTranslation } from './translate'; function Bounties (): React.ReactElement { const { t } = useTranslation(); - const { api } = useApi(); - const deriveBounties = useCall(api.derive.bounties.bounties); - const bestNumber = useCall(api.derive.chain.bestNumber); + const { bestNumber, bounties } = useBounties(); const headerRef = useRef([ [t('bounties'), 'start'], @@ -35,15 +30,15 @@ function Bounties (): React.ReactElement { return ( <> - + ('No open bounties')} + empty={bounties && t('No open bounties')} header={headerRef.current} > - {deriveBounties && bestNumber && deriveBounties.map(({ bounty, description, index, proposals }) => ( + {bounties && bestNumber && bounties.map(({ bounty, description, index, proposals }) => ( (null); + const balance = useBalance(accountId); + const [title, setTitle] = useState(''); - const [bond, setBond] = useState(((api.consts.bounties || api.consts.treasury).bountyDepositBase as BalanceOf).toBn()); + const [bond, setBond] = useState(bountyDepositBase); const [value, setValue] = useState(BOUNTY_DEFAULT_VALUE); const [isOpen, toggleIsOpen] = useToggle(); const [isTitleValid, setIsTitleValid] = useState(false); const [isValueValid, setIsValueValid] = useState(false); const [hasFunds, setHasFunds] = useState(false); - const balances = useCall(api.derive.balances.all, [accountId]); + useEffect(() => { + setIsTitleValid(title?.length >= MIN_TITLE_LEN && countUtf8Bytes(title) <= maximumReasonLength); + }, [maximumReasonLength, title]); useEffect(() => { - const bountyTitleMaxLength = ((api.consts.bounties || api.consts.treasury).maximumReasonLength as BalanceOf).toNumber(); - - setIsTitleValid(title?.length >= MIN_TITLE_LEN && countUtf8Bytes(title) <= bountyTitleMaxLength); - }, [api, title]); + setIsValueValid(!!value?.gte(bountyValueMinimum)); + }, [bountyValueMinimum, value]); useEffect(() => { - const bountyMinValue = ((api.consts.bounties || api.consts.treasury).bountyValueMinimum as BalanceOf).toBn(); - - setIsValueValid(!!value?.gte(bountyMinValue)); - }, [api, value]); - - useEffect(() => { - setHasFunds(!!balances?.availableBalance.gte(bond)); - }, [balances, bond]); + setHasFunds(!!balance?.gte(bond)); + }, [balance, bond]); const isValid = hasFunds && isTitleValid && isValueValid; const onTitleChange = useCallback((value: string) => { - const bountyBase = api.consts.bounties || api.consts.treasury; - const bountyDepositBase = bountyBase.bountyDepositBase; - const bountyDepositPerByte = bountyBase.dataDepositPerByte; - setTitle(value); - setBond(calculateBountyBond(value, bountyDepositBase as BalanceOf, bountyDepositPerByte as BalanceOf)); - }, [api]); + setBond(calculateBountyBond(value, bountyDepositBase, dataDepositPerByte)); + }, [bountyDepositBase, dataDepositPerByte]); return ( <> @@ -151,7 +140,7 @@ function BountyCreate () { label={t('Add Bounty')} onStart={toggleIsOpen} params={[value, title]} - tx={(api.tx.bounties || api.tx.treasury).proposeBounty} + tx={proposeBounty} /> diff --git a/packages/page-bounties/src/BountyInitiateVoting.tsx b/packages/page-bounties/src/BountyInitiateVoting.tsx index fe2fc42658..6f349105d0 100644 --- a/packages/page-bounties/src/BountyInitiateVoting.tsx +++ b/packages/page-bounties/src/BountyInitiateVoting.tsx @@ -1,4 +1,4 @@ -// Copyright 2017-2020 @polkadot/app-treasury authors & contributors +// Copyright 2017-2021 @polkadot/app-treasury authors & contributors // SPDX-License-Identifier: Apache-2.0 import type { DeriveCollectiveProposal } from '@polkadot/api-derive/types'; @@ -10,6 +10,7 @@ import { getTreasuryProposalThreshold } from '@polkadot/apps-config'; import { Button, InputAddress, Modal, TxButton } from '@polkadot/react-components'; import { useApi, useMembers, useToggle } from '@polkadot/react-hooks'; +import { useBounties } from './hooks'; import { useTranslation } from './translate'; interface Props { @@ -23,6 +24,7 @@ function BountyInitiateVoting ({ index, proposals }: Props): React.ReactElement< const { t } = useTranslation(); const { api } = useApi(); const { isMember, members } = useMembers(); + const { approveBounty, closeBounty } = useBounties(); const [isOpen, toggleOpen] = useToggle(); const [accountId, setAccountId] = useState(null); const [threshold, setThreshold] = useState(); @@ -33,8 +35,8 @@ function BountyInitiateVoting ({ index, proposals }: Props): React.ReactElement< ); }, [api, members]); - const approveBountyProposal = useRef((api.tx.bounties || api.tx.treasury).approveBounty(index)); - const closeBountyProposal = useRef((api.tx.bounties || api.tx.treasury).closeBounty(index)); + const approveBountyProposal = useRef(approveBounty(index)); + const closeBountyProposal = useRef(closeBounty(index)); const isVotingInitiated = useMemo(() => proposals?.filter(({ proposal }) => BOUNTY_METHODS.includes(proposal.method)).length !== 0, [proposals]); diff --git a/packages/page-bounties/src/Summary.tsx b/packages/page-bounties/src/Summary.tsx index 0b51b14b9e..c824117b78 100644 --- a/packages/page-bounties/src/Summary.tsx +++ b/packages/page-bounties/src/Summary.tsx @@ -1,17 +1,14 @@ // Copyright 2017-2020 @polkadot/app-bounties authors & contributors // SPDX-License-Identifier: Apache-2.0 -import type { BountyIndex } from '@polkadot/types/interfaces'; - import React from 'react'; +import { useBounties } from '@polkadot/app-bounties/hooks'; import { useTranslation } from '@polkadot/app-treasury/translate'; import { CardSummary, SummaryBox } from '@polkadot/react-components'; import Progress from '@polkadot/react-components/Progress'; -import { useApi, useCall } from '@polkadot/react-hooks'; import { useTreasury } from '@polkadot/react-hooks/useTreasury'; import { BlockToTime, FormatBalance } from '@polkadot/react-query'; -import { Balance } from '@polkadot/types/interfaces'; interface Props { activeBounties?: number; @@ -20,10 +17,7 @@ interface Props { function Summary ({ activeBounties, className = '' }: Props): React.ReactElement { const { t } = useTranslation(); - const { api } = useApi(); - - const bountyIndex = useCall((api.query.bounties || api.query.treasury).bountyCount); - const bestNumber = useCall(api.derive.chain.bestNumber); + const { bestNumber, bountyIndex } = useBounties(); const { burn, spendPeriod, value } = useTreasury(); diff --git a/packages/page-bounties/src/helpers/calculateBountyBond.ts b/packages/page-bounties/src/helpers/calculateBountyBond.ts index a3a9baa1e3..c43939f087 100644 --- a/packages/page-bounties/src/helpers/calculateBountyBond.ts +++ b/packages/page-bounties/src/helpers/calculateBountyBond.ts @@ -1,12 +1,10 @@ // Copyright 2017-2021 @polkadot/app-bounties authors & contributors // SPDX-License-Identifier: Apache-2.0 -import type { BalanceOf } from '@polkadot/types/interfaces'; - import BN from 'bn.js'; -export function calculateBountyBond (description: string, depositBase: BalanceOf, depositPerByte: BalanceOf): BN { - return depositBase.toBn().add(depositPerByte.toBn().muln(countUtf8Bytes(description))); +export function calculateBountyBond (description: string, depositBase: BN, depositPerByte: BN): BN { + return depositBase.add(depositPerByte.muln(countUtf8Bytes(description))); } export function countUtf8Bytes (str: string): number { diff --git a/packages/page-bounties/src/hooks/index.ts b/packages/page-bounties/src/hooks/index.ts new file mode 100644 index 0000000000..ca481da2ca --- /dev/null +++ b/packages/page-bounties/src/hooks/index.ts @@ -0,0 +1,5 @@ +// Copyright 2017-2021 @polkadot/app-bounties authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +export * from './useBounties'; +export * from './useBalance'; diff --git a/packages/page-bounties/src/hooks/useBalance.ts b/packages/page-bounties/src/hooks/useBalance.ts new file mode 100644 index 0000000000..a9943a6b10 --- /dev/null +++ b/packages/page-bounties/src/hooks/useBalance.ts @@ -0,0 +1,13 @@ +// Copyright 2017-2021 @polkadot/app-bounties authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +import type { Balance } from '@polkadot/types/interfaces'; + +import { DeriveBalancesAll } from '@polkadot/api-derive/types'; +import { useApi, useCall } from '@polkadot/react-hooks'; + +export function useBalance (accountId: string | null): Balance | undefined { + const { api } = useApi(); + + return useCall(api.derive.balances.all, [accountId])?.availableBalance; +} diff --git a/packages/page-bounties/src/hooks/useBounties.tsx b/packages/page-bounties/src/hooks/useBounties.tsx new file mode 100644 index 0000000000..d7eb5c9310 --- /dev/null +++ b/packages/page-bounties/src/hooks/useBounties.tsx @@ -0,0 +1,51 @@ +// Copyright 2017-2021 @polkadot/app-bounties authors & contributors +// SPDX-License-Identifier: Apache-2.0 + +import type { SubmittableExtrinsic } from '@polkadot/api/types'; + +import BN from 'bn.js'; + +import { DeriveBounties } from '@polkadot/api-derive/types'; +import { useApi, useCall } from '@polkadot/react-hooks'; +import { BalanceOf, BlockNumber, BountyIndex } from '@polkadot/types/interfaces'; + +export type BountyApi = { + approveBounty: ((...args: any[]) => SubmittableExtrinsic<'promise'>); + bestNumber?: BlockNumber, + bounties?: DeriveBounties, + bountyDepositBase: BN, + bountyIndex?: BN, + bountyValueMinimum: BN, + closeBounty: ((...args: any[]) => SubmittableExtrinsic<'promise'>); + dataDepositPerByte: BN, + maximumReasonLength: number, + proposeBounty: ((...args: any[]) => SubmittableExtrinsic<'promise'>); +}; + +export function useBounties (): BountyApi { + const { api } = useApi(); + const bounties = useCall(api.derive.bounties.bounties); + const bountyIndex = useCall((api.query.bounties || api.query.treasury).bountyCount); + const bestNumber = useCall(api.derive.chain.bestNumber); + const constsBase = api.consts.bounties || api.consts.treasury; + const bountyDepositBase = (constsBase.bountyDepositBase as BalanceOf).toBn(); + const bountyValueMinimum = (constsBase.bountyValueMinimum as BalanceOf).toBn(); + const maximumReasonLength = constsBase.maximumReasonLength.toNumber(); + const dataDepositPerByte = (constsBase.dataDepositPerByte as BalanceOf).toBn(); + const proposeBounty = (api.tx.bounties || api.tx.treasury).proposeBounty; + const approveBounty = (api.tx.bounties || api.tx.treasury).approveBounty; + const closeBounty = (api.tx.bounties || api.tx.treasury).closeBounty; + + return { + approveBounty, + bestNumber, + bounties, + bountyDepositBase, + bountyIndex, + bountyValueMinimum, + closeBounty, + dataDepositPerByte, + maximumReasonLength, + proposeBounty + }; +}