Skip to content

Commit

Permalink
✅ e2e: add rollover tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jgalat committed Sep 22, 2023
1 parent 3895ef9 commit d55b923
Show file tree
Hide file tree
Showing 17 changed files with 296 additions and 19 deletions.
14 changes: 12 additions & 2 deletions components/DebtManager/Operation/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,7 @@ function Operation() {
open={fromSheetOpen}
onClose={onClose}
title={t('Select Current Debt')}
data-testid="rollover-sheet-from"
>
<PositionTable
loading={fromRows.length === 0}
Expand All @@ -477,6 +478,7 @@ function Operation() {
open={toSheetOpen}
onClose={onClose}
title={t('Select New Debt')}
data-testid="rollover-sheet-to"
>
<Box display="flex" justifyContent="space-between">
<Typography variant="caption" color="figma.grey.600">
Expand Down Expand Up @@ -526,6 +528,7 @@ function Operation() {
selected={Boolean(input.from)}
onClick={() => setSheetOpen([true, false])}
sx={{ ml: -0.5 }}
data-testid="rollover-from"
>
{input.from ? (
<>
Expand All @@ -536,7 +539,12 @@ function Operation() {
t('Current debt')
)}
</ModalSheetButton>
<Typography component="div" variant="subtitle1" color="figma.grey.500">
<Typography
component="div"
variant="subtitle1"
color="figma.grey.500"
data-testid="rollover-from-label"
>
{input.from
? input.from.maturity
? parseTimestamp(input.from.maturity)
Expand All @@ -558,6 +566,7 @@ function Operation() {
}}
disabled={!input.from}
sx={{ ml: -0.5, mr: -0.5 }}
data-testid="rollover-to"
>
{input.to ? (
<>
Expand All @@ -568,7 +577,7 @@ function Operation() {
t('New debt')
)}
</ModalSheetButton>
<Typography component="div" variant="subtitle1" color="figma.grey.500">
<Typography component="div" variant="subtitle1" color="figma.grey.500" data-testid="rollover-to-label">
{input.to ? (input.to.maturity ? parseTimestamp(input.to.maturity) : t('Open-ended')) : t('Maturity')}
</Typography>
</Grid>
Expand All @@ -588,6 +597,7 @@ function Operation() {
</Box>
{errorData?.status && <ModalAlert message={errorData.message} variant={errorData.variant} />}
<Submit
data-testid={requiresApproval ? 'rollover-approve' : 'rollover-submit'}
disabled={!input.from || !input.to || errorData?.status}
loading={loadingStatus || isLoading}
onClick={requiresApproval ? approveRollover : rollover}
Expand Down
1 change: 1 addition & 0 deletions components/DebtManager/PositionTable/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ function PositionTable({ data, onClick, loading = false, showBalance = false }:
cursor: 'pointer',
}}
onClick={() => onClick(row)}
data-testid={`rollover-sheet-row-${row.symbol}${row.maturity ? `-${row.maturity}` : ''}`}
>
<TableCell sx={{ maxWidth: 64 }}>
<AssetCell symbol={row.symbol} />
Expand Down
2 changes: 2 additions & 0 deletions components/DebtManager/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,11 @@ function DebtManagerModal({ isOpen, close }: Props) {
sx={isMobile ? { top: 'auto' } : { backdropFilter: tx ? 'blur(1.5px)' : '' }}
BackdropProps={{ style: { backgroundColor: tx ? 'rgb(100, 100, 100 , 0.1)' : '' } }}
disableEscapeKeyDown={loadingTx}
data-testid="rollover-modal"
>
{!loadingTx && (
<IconButton
data-testid="rollover-modal-close"
aria-label="close"
onClick={close}
sx={{
Expand Down
4 changes: 2 additions & 2 deletions components/common/modal/Loading/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,12 @@ function Loading({ tx, maturity, messages: { pending, success, error } = {} }: P
/>
)}
<Box display="flex" flexDirection="column" alignItems="center">
<Typography variant="h6" fontSize="16px">
<Typography variant="h6" fontSize="16px" data-testid="transaction-status">
{isLoading && t('Processing transaction...')}
{isSuccess && t('Transaction completed')}
{isError && t('Transaction error')}
</Typography>
<Typography fontSize="14px" fontWeight={500} color="grey.500">
<Typography fontSize="14px" fontWeight={500} color="grey.500" data-testid="transaction-summary">
{isLoading && pending}
{isSuccess && success}
{isError && error}
Expand Down
8 changes: 5 additions & 3 deletions components/common/modal/ModalSheet/index.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import React, { forwardRef, type PropsWithChildren } from 'react';
import { Box, IconButton, Typography, useTheme, Slide, SlideProps, Backdrop } from '@mui/material';
import { Box, IconButton, Typography, useTheme, Slide, SlideProps, Backdrop, BoxProps } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';

type Props = PropsWithChildren<{
container: SlideProps['container'];
title?: string;
open: boolean;
onClose: () => void;
}>;
}> &
BoxProps;

const ModalSheet = forwardRef(function ModalSheet({ title, container, open, onClose, children }: Props, ref) {
const ModalSheet = forwardRef(function ModalSheet({ title, container, open, onClose, children, ...props }: Props, ref) {
const { spacing, palette } = useTheme();

return (
Expand All @@ -29,6 +30,7 @@ const ModalSheet = forwardRef(function ModalSheet({ title, container, open, onCl
zIndex: 2,
overflowY: 'hidden',
}}
{...props}
>
<IconButton
aria-label="close"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ function TableRowFixedPool({ symbol, valueUSD, type, maturityDate, market, decim
}}
onClick={() => startDebtManager({ from: { symbol, maturity: maturityDate } })}
disabled={isRolloverDisabled()}
data-testid={`fixed-rollover-${maturityDate}-${symbol}`}
>
{t('Rollover')}
</Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ function TableRowFloatingPool({ symbol, valueUSD, depositedAmount, borrowedAmoun
<TableRow
sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
hover
data-testid={`dashboard-floating-pool-row-${symbol}`}
data-testid={`dashboard-floating-${type}-row-${symbol}`}
>
<Link href={{ pathname: `/${symbol}`, query }} legacyBehavior>
<TableCell component="th" align="left" sx={{ cursor: 'pointer', pl: 1.5 }} width={240}>
Expand Down Expand Up @@ -128,6 +128,7 @@ function TableRowFloatingPool({ symbol, valueUSD, depositedAmount, borrowedAmoun
}}
onClick={() => startDebtManager({ from: { symbol } })}
disabled={isRolloverDisabled(borrowedAmount)}
data-testid={`floating-rollover-${symbol}`}
>
{t('Rollover')}
</Button>
Expand Down
2 changes: 1 addition & 1 deletion components/operations/Faucet/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function Faucet() {
setLoading(symbol);
const amounts: Record<string, string> = {
DAI: '50000',
USDC: '50000000',
USDC: '50000',
WBTC: '2',
};

Expand Down
1 change: 1 addition & 0 deletions contexts/DebtManagerContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ export const DebtManagerContextProvider: FC<PropsWithChildren<Props>> = ({ args,

await refreshAccountData();
} catch (e: unknown) {
console.log(e);

Check failure on line 166 in contexts/DebtManagerContext.tsx

View workflow job for this annotation

GitHub Actions / check

Unexpected console statement
track.removeFromCart('roll', input);
setErrorData({ status: true, message: handleOperationError(e) });
} finally {
Expand Down
13 changes: 7 additions & 6 deletions e2e/common/balance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,20 @@ export default function ({ test, publicClient }: CommonTest & { publicClient: Pu
address: Address;
symbol: ERC20TokenSymbol;
amount: string;
delta?: number;
delta?: string;
};

const check = async ({ address, symbol, amount, delta }: BalanceParams) => {
await test.step(`checks ${symbol} balance to be ${delta ? 'near ' : ''}${amount}`, async () => {
const check = async ({ address, symbol, amount, delta: _delta }: BalanceParams) => {
await test.step(`checks ${symbol} balance to be ${_delta ? 'near ' : ''}${amount}`, async () => {
const erc20Contract = await erc20(symbol, { publicClient });
const balance = await erc20Contract.read.balanceOf([address]);
const decimals = await erc20Contract.read.decimals();
const expected = parseUnits(amount, decimals);
if (delta) {
if (_delta) {
const wad = parseUnits('1', decimals);
const lower = (expected * parseUnits(String(1 - delta), decimals)) / wad;
const upper = (expected * parseUnits(String(1 + delta), decimals)) / wad;
const delta = parseUnits(_delta, decimals);
const lower = (expected * (wad - delta)) / wad;
const upper = (expected * (wad + delta)) / wad;

expect(balance > lower).toBe(true);
expect(balance < upper).toBe(true);
Expand Down
1 change: 1 addition & 0 deletions e2e/components/modal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export default function (page: Page) {
await page.getByTestId(`${type}-${maturity ? `${maturity}-` : ''}${action}-${symbol}`).click();
await waitForModalReady();
};

const close = async () => {
await page.getByTestId('modal-close').click();
await expect(page.getByTestId('modal')).not.toBeVisible();
Expand Down
117 changes: 117 additions & 0 deletions e2e/components/rollover.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { type Page, expect } from '@playwright/test';

import type { ERC20TokenSymbol } from '../utils/contracts';
import { formatMaturity } from '../utils/strings';

export default function (page: Page) {
const waitForModalReady = async () => {
const modal = page.getByTestId('rollover-modal');
await expect(modal).toBeVisible();

await page.waitForFunction(
() => {
return ['submit', 'approve'].every((action) => {
const button = document.querySelector(`[data-testid="rollover-${action}"]`);
if (!button) return true;
return !button.classList.contains('MuiLoadingButton-loading');
});
},
null,
{
timeout: 30_000,
polling: 1_000,
},
);
};

const cta = (type: 'floating' | 'fixed', symbol: ERC20TokenSymbol, maturity?: number) => {
return page.getByTestId(`${type}-rollover${maturity ? `-${maturity}` : ''}-${symbol}`);
};

const open = async (type: 'floating' | 'fixed', symbol: ERC20TokenSymbol, maturity?: number) => {
await cta(type, symbol, maturity).click();
await waitForModalReady();
};

const close = async () => {
await page.getByTestId('rollover-modal-close').click();
await expect(page.getByTestId('rollover-modal')).not.toBeVisible();
};

const checkOption = async (
option: 'from' | 'to',
stats: { type: 'empty' } | { type: 'floating' } | { type: 'fixed'; maturity: number },
) => {
const button = page.getByTestId(`rollover-${option}`);
const label = page.getByTestId(`rollover-${option}-label`);
switch (stats.type) {
case 'empty':
await expect(button).toHaveText(option === 'from' ? 'Current debt' : 'New debt');
await expect(label).toHaveText('Maturity');
break;
case 'floating':
await expect(button).toHaveText('Variable');
await expect(label).toHaveText('Open-ended');
break;
case 'fixed':
await expect(button).toHaveText('Fixed');
await expect(label).toHaveText(formatMaturity(stats.maturity));
break;
}
};

const openSheet = async (option: 'from' | 'to') => {
await page.getByTestId(`rollover-${option}`).click();
await expect(page.getByTestId(`rollover-sheet-${option}`)).toBeVisible();
};

const selectDebt = async (symbol: ERC20TokenSymbol, maturity?: number) => {
const row = page.getByTestId(`rollover-sheet-row-${symbol}${maturity ? `-${maturity}` : ''}`);
await expect(row).toBeVisible();
await row.click();
};

const submit = async () => {
const button = page.getByTestId('rollover-submit');
await expect(button).toBeVisible();
await expect(button).not.toBeDisabled();

await button.click();
};

const waitForTransaction = async () => {
const status = page.getByTestId('transaction-status');

await expect(status).toBeVisible({ timeout: 30_000 });

await page.waitForFunction(
(message) => {
const text = document.querySelector('[data-testid="transaction-status"]');
if (!text) return false;
return text.textContent !== message;
},
'Processing transaction...',
{ timeout: 30_000, polling: 1_000 },
);
};

const checkTransactionStatus = async (target: 'success' | 'error', summary: string) => {
const status = page.getByTestId('transaction-status');

await expect(status).toHaveText(`Transaction ${target === 'success' ? 'completed' : target}`);
await expect(page.getByTestId('transaction-summary')).toHaveText(summary);
};

return {
waitForModalReady,
cta,
open,
close,
checkOption,
openSheet,
selectDebt,
submit,
waitForTransaction,
checkTransactionStatus,
};
}
6 changes: 6 additions & 0 deletions e2e/page/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ export default function (page: Page) {
await t.click();
};

const checkFloatingTableRow = async (type: 'deposit' | 'borrow', symbol: ERC20TokenSymbol) => {
const row = page.getByTestId(`dashboard-floating-${type}-row-${symbol}`);
await expect(row).toBeVisible();
};

const checkFixedTableRow = async (type: 'deposit' | 'borrow', symbol: ERC20TokenSymbol, maturity: number) => {
const row = page.getByTestId(`dashboard-fixed-${type}-row-${maturity}-${symbol}`);
await expect(row).toBeVisible();
Expand All @@ -77,6 +82,7 @@ export default function (page: Page) {
attemptEnterMarket,
attemptExitMarket,
switchTab,
checkFloatingTableRow,
checkFixedTableRow,
waitForTransaction,
};
Expand Down
2 changes: 1 addition & 1 deletion e2e/specs/4-fixed-borrow-repay/op.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,5 @@ test('OP fixed borrow/repay', async ({ page, web3, setup }) => {
maturity: pool,
});

await balance.check({ address: web3.account.address, symbol: 'OP', amount: '52', delta: 0.005 });
await balance.check({ address: web3.account.address, symbol: 'OP', amount: '52', delta: '0.005' });
});
Loading

0 comments on commit d55b923

Please sign in to comment.