Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: migrate use of @testing-library/react-hooks #867

Merged
merged 15 commits into from
May 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions packages/arb-token-bridge-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,12 @@
"devDependencies": {
"@next/eslint-plugin-next": "^13.1.5",
"@synthetixio/synpress": "^3.5.1",
"@testing-library/react-hooks": "^8.0.1",
"@testing-library/react": "^14.0.0",
"@types/jest": "^29.5.1",
"@types/lodash-es": "^4.17.6",
"@types/node": "^16.6.1",
"@types/react": "^17.0.18",
"@types/react-dom": "^17.0.9",
"@types/react": "^18.2.6",
"@types/react-dom": "^18.2.4",
"@types/react-virtualized": "^9.21.20",
"@typescript-eslint/eslint-plugin": "^5.57.0",
"@typescript-eslint/parser": "^5.44.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,38 +46,40 @@ export const NetworkSelectionContainer = ({

<Transition>
<Popover.Panel className="relative flex flex-col rounded-md lg:absolute lg:ml-1 lg:mt-1 lg:bg-white lg:shadow-[0px_4px_20px_rgba(0,0,0,0.2)]">
{({ close }) =>
supportedNetworks?.map((chainId, i) => (
<div // TODO: replace with button
key={chainId}
className="flex h-12 cursor-pointer flex-nowrap items-center justify-start space-x-3 px-12 text-lg font-light text-white hover:bg-[rgba(0,0,0,0.2)] lg:px-4 lg:text-base lg:font-normal lg:text-dark"
onClick={() => {
handleClick(chainId, close)
}}
onKeyDown={e => {
if (e.key === 'Enter' || e.keyCode === 13) {
{({ close }) => (
<>
{supportedNetworks?.map((chainId, i) => (
<div // TODO: replace with button
key={chainId}
className="flex h-12 cursor-pointer flex-nowrap items-center justify-start space-x-3 px-12 text-lg font-light text-white hover:bg-[rgba(0,0,0,0.2)] lg:px-4 lg:text-base lg:font-normal lg:text-dark"
onClick={() => {
handleClick(chainId, close)
}
}}
role="button"
tabIndex={i}
aria-label={`Switch to ${getNetworkName(Number(chainId))}`}
>
<div className="flex h-6 w-6 items-center justify-center lg:h-8 lg:w-8">
<Image
src={getNetworkLogo(Number(chainId))}
alt={`${getNetworkName(Number(chainId))} logo`}
className="h-full w-auto"
width={24}
height={24}
/>
}}
onKeyDown={e => {
if (e.key === 'Enter' || e.keyCode === 13) {
handleClick(chainId, close)
}
}}
role="button"
tabIndex={i}
aria-label={`Switch to ${getNetworkName(Number(chainId))}`}
>
<div className="flex h-6 w-6 items-center justify-center lg:h-8 lg:w-8">
<Image
src={getNetworkLogo(Number(chainId))}
alt={`${getNetworkName(Number(chainId))} logo`}
className="h-full w-auto"
width={24}
height={24}
/>
</div>
<span className="whitespace-nowrap">
{getNetworkName(Number(chainId))}
</span>
</div>
<span className="whitespace-nowrap">
{getNetworkName(Number(chainId))}
</span>
</div>
))
}
))}
</>
)}
</Popover.Panel>
</Transition>
</Popover>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function RetryableTxnsIncluder(): JSX.Element {
} = useAppState()

const fetchAndUpdateDepositStatus = useCallback(
async (depositTxId, depositAssetType) => {
async (depositTxId: string, depositAssetType: AssetType | string) => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@types/react & @types/react-dom v17 for some reason allow it to be of type any and won't throw an error but v18 will

const isEthDeposit = depositAssetType === AssetType.ETH

const { l1ToL2Msg, isClassic } = await getL1ToL2MessageDataFromL1TxHash({
Expand Down
169 changes: 77 additions & 92 deletions packages/arb-token-bridge-ui/src/hooks/__tests__/useBalance.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@
* @jest-environment jsdom
*/

import { act, renderHook } from '@testing-library/react-hooks'
import { RenderHookResult, act, renderHook } from '@testing-library/react'
import { StaticJsonRpcProvider } from '@ethersproject/providers'
import { BigNumber } from 'ethers'
import { SWRConfig } from 'swr'
import { PropsWithChildren } from 'react'
import { MultiCaller } from '@arbitrum/sdk'
import { useBalance } from '../useBalance'

import { UseBalanceProps, useBalance } from '../useBalance'

// Create a new cache for every test
const Container = ({ children }: PropsWithChildren<unknown>) => (
Expand All @@ -17,6 +18,27 @@ const Container = ({ children }: PropsWithChildren<unknown>) => (

const walletAddress = '0x58b6a8a3302369daec383334672404ee733ab239'

const renderHookAsyncUseBalance = async ({
provider,
walletAddress
}: UseBalanceProps) => {
let hook:
| RenderHookResult<ReturnType<typeof useBalance>, UseBalanceProps>
| undefined

await act(async () => {
hook = renderHook(() => useBalance({ provider, walletAddress }), {
wrapper: Container
})
})

if (!hook) {
throw new Error('Hook is not defined')
}

return { result: hook.result }
}

describe('useBalance', () => {
afterEach(() => {
jest.restoreAllMocks()
Expand All @@ -42,16 +64,10 @@ describe('useBalance', () => {
])
)

const { result, waitForNextUpdate } = renderHook(
() =>
useBalance({
provider,
walletAddress: undefined
}),
{ wrapper: Container }
)

await waitForNextUpdate({ timeout: 250 })
const { result } = await renderHookAsyncUseBalance({
provider,
walletAddress: undefined
})

const {
current: {
Expand Down Expand Up @@ -89,18 +105,10 @@ describe('useBalance', () => {
])
)

const { result, waitForNextUpdate } = renderHook(
() =>
useBalance({
provider,
walletAddress
}),
{ wrapper: Container }
)

try {
await waitForNextUpdate({ timeout: 100 })
} catch (err) {}
const { result } = await renderHookAsyncUseBalance({
provider,
walletAddress
})

const {
current: {
Expand Down Expand Up @@ -135,16 +143,11 @@ describe('useBalance', () => {
])
)

const { result, waitForNextUpdate } = renderHook(
() =>
useBalance({
provider,
walletAddress
}),
{ wrapper: Container }
)
const { result } = await renderHookAsyncUseBalance({
provider,
walletAddress
})

await waitForNextUpdate({ timeout: 100 })
expect(result.current.eth[0]?.toNumber()).toEqual(32)
expect(getBalanceSpy).toHaveBeenCalledTimes(1)
expect(getBalanceSpy).toHaveBeenCalledWith(walletAddress)
Expand All @@ -170,16 +173,10 @@ describe('useBalance', () => {
])
)

const { result, waitForNextUpdate } = renderHook(
() =>
useBalance({
provider,
walletAddress
}),
{ wrapper: Container }
)

await waitForNextUpdate({ timeout: 100 })
const { result } = await renderHookAsyncUseBalance({
provider,
walletAddress
})

const {
current: {
Expand All @@ -191,8 +188,9 @@ describe('useBalance', () => {
expect(getBalanceSpy).toHaveBeenCalledTimes(1)
expect(getBalanceSpy).toHaveBeenCalledWith(walletAddress)

updateEthBalance()
await waitForNextUpdate({ timeout: 100 })
await act(async () => {
updateEthBalance()
})

const {
current: {
Expand Down Expand Up @@ -233,14 +231,10 @@ describe('useBalance', () => {
])
)

const { result, waitForValueToChange } = renderHook(
() =>
useBalance({
provider,
walletAddress
}),
{ wrapper: Container }
)
const { result } = await renderHookAsyncUseBalance({
provider,
walletAddress
})
const {
current: {
erc20: [, updateErc20Balances]
Expand All @@ -252,9 +246,7 @@ describe('useBalance', () => {
'0x0000000000000000000000000000000000000001',
'0x0000000000000000000000000000000000000002'
]
updateErc20Balances(erc20)

await waitForValueToChange(() => result.current.erc20, { timeout: 100 })
await act(async () => updateErc20Balances(erc20))

expect(result.current.erc20[0]).toEqual({
'0x0000000000000000000000000000000000000000': BigNumber.from(10),
Expand Down Expand Up @@ -290,14 +282,10 @@ describe('useBalance', () => {
])
)

const { result, waitForValueToChange } = renderHook(
() =>
useBalance({
provider,
walletAddress
}),
{ wrapper: Container }
)
const { result } = await renderHookAsyncUseBalance({
provider,
walletAddress
})
const {
current: {
erc20: [, updateErc20Balances]
Expand All @@ -308,9 +296,7 @@ describe('useBalance', () => {
'0xABCdef0000000000000000000000000000000000',
'0xAAADDD0000000000000000000000000000000001'
]
updateErc20Balances(erc20)

await waitForValueToChange(() => result.current.erc20, { timeout: 100 })
await act(async () => updateErc20Balances(erc20))

const {
current: {
Expand Down Expand Up @@ -339,32 +325,31 @@ describe('useBalance', () => {
}
])
)
})
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assertions shouldn't be wrapped in the same act function as it was previously


const newAddresses = [
'0xAaADDD0000000000000000000000000000000001',
'0xAAAAAA0000000000000000000000000000000002'
]
await act(async () => updateErc20Balances(newAddresses))

/**
* 0x..0 is untouched
* 0x..1 is updated
* 0x..2 is added
*
* All balances are stored in lowercase
*/
expect(result.current.erc20[0]).toEqual({
'0xabcdef0000000000000000000000000000000000': BigNumber.from(11),
'0xaaaddd0000000000000000000000000000000001': BigNumber.from(25),
'0xaaaaaa0000000000000000000000000000000002': BigNumber.from(33)
})

const newAddresses = [
'0xAaADDD0000000000000000000000000000000001',
'0xAAAAAA0000000000000000000000000000000002'
]
updateErc20Balances(newAddresses)
await waitForValueToChange(() => result.current.erc20, { timeout: 500 })

/**
* 0x..0 is untouched
* 0x..1 is updated
* 0x..2 is added
*
* All balances are stored in lowercase
*/
expect(result.current.erc20[0]).toEqual({
'0xabcdef0000000000000000000000000000000000': BigNumber.from(11),
'0xaaaddd0000000000000000000000000000000001': BigNumber.from(25),
'0xaaaaaa0000000000000000000000000000000002': BigNumber.from(33)
})

expect(getBalanceSpy).toHaveBeenCalledTimes(1)
expect(getTokenDataSpy).toHaveBeenCalledTimes(2)
expect(getTokenDataSpy).toHaveBeenLastCalledWith(newAddresses, {
balanceOf: { account: walletAddress }
})
expect(getBalanceSpy).toHaveBeenCalledTimes(1)
expect(getTokenDataSpy).toHaveBeenCalledTimes(2)
expect(getTokenDataSpy).toHaveBeenLastCalledWith(newAddresses, {
balanceOf: { account: walletAddress }
})
})
})
Expand Down
13 changes: 6 additions & 7 deletions packages/arb-token-bridge-ui/src/hooks/useBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ type Erc20Balances = {
[address: string]: BigNumber | undefined
}

export type UseBalanceProps = {
provider: Provider
walletAddress: string | undefined
}

const merge: Middleware = (useSWRNext: SWRHook) => {
return (key, fetcher, config) => {
const { cache } = useSWRConfig()
Expand All @@ -35,13 +40,7 @@ const merge: Middleware = (useSWRNext: SWRHook) => {
}
}

const useBalance = ({
provider,
walletAddress
}: {
provider: Provider
walletAddress: string | undefined
}) => {
const useBalance = ({ provider, walletAddress }: UseBalanceProps) => {
const chainId = useChainId({ provider })
const walletAddressLowercased = useMemo(
() => walletAddress?.toLowerCase(),
Expand Down
Loading