chore(trading): remove noise form the test logs (#2801)

This commit is contained in:
macqbat 2023-02-01 16:58:47 +01:00 committed by GitHub
parent b2489537ef
commit fb1ebb3bdf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 243 additions and 178 deletions

View File

@ -49,7 +49,6 @@ describe('NodeHealth', () => {
it.each(cases)(
'renders correct text and indicator color for $diff block difference',
(elem) => {
console.log(elem);
render(<NodeHealth blockDiff={elem.diff} openNodeSwitcher={jest.fn()} />);
expect(screen.getByTestId('indicator')).toHaveClass(elem.classname);
expect(screen.getByText(elem.text)).toBeInTheDocument();

View File

@ -151,6 +151,8 @@ const MARKET_B: PartialMarket = {
};
describe('SelectMarket', () => {
const table = document.createElement('table');
it('should render the SelectAllMarketsTableBody', () => {
const onSelect = jest.fn();
const onCellClick = jest.fn();
@ -162,7 +164,7 @@ describe('SelectMarket', () => {
onSelect={onSelect}
/>
</MemoryRouter>,
{ wrapper: MockedProvider }
{ wrapper: MockedProvider, container: document.body.appendChild(table) }
);
expect(screen.getByText('ABCDEF')).toBeTruthy(); // name
expect(screen.getByText('25.00%')).toBeTruthy(); // price change

View File

@ -59,14 +59,17 @@ describe('AccountManager', () => {
await waitFor(() => {
expect(screen.getByText('No accounts')).toBeInTheDocument();
});
expect(mockedUpdate({ data: [] })).toEqual(true);
expect(
mockedUpdate({ data: [{ party: { id: 't1' } }] as AccountFields[] })
).toEqual(false);
expect(
mockedUpdate({ data: [{ party: { id: 't2' } }] as AccountFields[] })
).toEqual(true);
expect(mockedUpdate({ data: [] })).toEqual(false);
expect(mockedUpdate({ data: [] })).toEqual(true);
await act(() => {
expect(mockedUpdate({ data: [] })).toEqual(true);
expect(
mockedUpdate({ data: [{ party: { id: 't1' } }] as AccountFields[] })
).toEqual(false);
expect(
mockedUpdate({ data: [{ party: { id: 't2' } }] as AccountFields[] })
).toEqual(true);
expect(mockedUpdate({ data: [] })).toEqual(false);
expect(mockedUpdate({ data: [] })).toEqual(true);
});
});
});

View File

@ -185,7 +185,7 @@ export const DepositForm = ({
hasError={Boolean(errors.asset?.message)}
>
{assets.filter(isAssetTypeERC20).map((a) => (
<AssetOption asset={a} />
<AssetOption asset={a} key={a.id} />
))}
</RichSelect>
)}

View File

@ -82,8 +82,9 @@ describe('FillsTable', () => {
liquidityFee: '2',
},
});
render(<FillsTable partyId={partyId} rowData={[{ ...buyerFill }]} />);
await act(async () => {
render(<FillsTable partyId={partyId} rowData={[{ ...buyerFill }]} />);
});
await waitForGridToBeInTheDOM();
await waitForDataToHaveLoaded();
@ -119,8 +120,9 @@ describe('FillsTable', () => {
liquidityFee: '1',
},
});
render(<FillsTable partyId={partyId} rowData={[buyerFill]} />);
await act(async () => {
render(<FillsTable partyId={partyId} rowData={[buyerFill]} />);
});
await waitForGridToBeInTheDOM();
await waitForDataToHaveLoaded();
@ -150,10 +152,13 @@ describe('FillsTable', () => {
},
aggressor: Schema.Side.SIDE_SELL,
});
const { rerender } = render(
<FillsTable partyId={partyId} rowData={[takerFill]} />
);
let rerenderer: (ui: React.ReactElement) => void;
await act(async () => {
const { rerender } = render(
<FillsTable partyId={partyId} rowData={[takerFill]} />
);
rerenderer = rerender;
});
await waitForGridToBeInTheDOM();
await waitForDataToHaveLoaded();
@ -169,8 +174,9 @@ describe('FillsTable', () => {
},
aggressor: Schema.Side.SIDE_BUY,
});
rerender(<FillsTable partyId={partyId} rowData={[makerFill]} />);
await act(async () => {
rerenderer(<FillsTable partyId={partyId} rowData={[makerFill]} />);
});
await waitForGridToBeInTheDOM();
await waitForDataToHaveLoaded();
@ -189,7 +195,7 @@ describe('FillsTable', () => {
},
aggressor: Schema.Side.SIDE_SELL,
});
act(() => {
await act(async () => {
render(<FillsTable partyId={partyId} rowData={[takerFill]} />);
});
await waitForGridToBeInTheDOM();
@ -206,11 +212,12 @@ describe('FillsTable', () => {
await waitFor(() => {
expect(feeCell).toBeInTheDocument();
});
act(() => {
await act(async () => {
userEvent.hover(feeCell as HTMLElement);
await new Promise((res) => setTimeout(() => res(true), 1000));
});
await waitFor(() => {
await act(async () => {
expect(screen.getByTestId('fee-breakdown-tooltip')).toBeInTheDocument();
});
});

View File

@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react';
import { render, screen, act } from '@testing-library/react';
import { OrderListManager } from './order-list-manager';
import * as useDataProviderHook from '@vegaprotocol/react-helpers';
import type { OrderFieldsFragment } from '../';
@ -19,7 +19,7 @@ const generateJsx = () => {
);
};
it('Renders a loading state while awaiting orders', () => {
it('Renders a loading state while awaiting orders', async () => {
jest.spyOn(useDataProviderHook, 'useDataProvider').mockReturnValue({
data: [],
loading: true,
@ -29,11 +29,13 @@ it('Renders a loading state while awaiting orders', () => {
load: jest.fn(),
totalCount: 0,
});
render(generateJsx());
await act(async () => {
render(generateJsx());
});
expect(screen.getByText('Loading...')).toBeInTheDocument();
});
it('Renders an error state', () => {
it('Renders an error state', async () => {
const errorMsg = 'Oops! An Error';
jest.spyOn(useDataProviderHook, 'useDataProvider').mockReturnValue({
data: [],
@ -44,7 +46,9 @@ it('Renders an error state', () => {
load: jest.fn(),
totalCount: undefined,
});
render(generateJsx());
await act(async () => {
render(generateJsx());
});
expect(
screen.getByText(`Something went wrong: ${errorMsg}`)
).toBeInTheDocument();
@ -63,6 +67,8 @@ it('Renders the order list if orders provided', async () => {
load: jest.fn(),
totalCount: undefined,
});
render(generateJsx());
await act(async () => {
render(generateJsx());
});
expect(await screen.findByText('OrderList')).toBeInTheDocument();
});

View File

@ -1,4 +1,4 @@
import { renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react-hooks';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import type { ReactNode } from 'react';
@ -33,6 +33,7 @@ const render = (mocks?: MockedResponse[]) => {
const wrapper = ({ children }: { children: ReactNode }) => (
<MockedProvider mocks={mocks}>{children}</MockedProvider>
);
return renderHook(() => useVegaTransactionUpdater(), { wrapper });
};
@ -193,19 +194,23 @@ describe('useVegaTransactionManager', () => {
it('updates order on OrderBusEvents', async () => {
mockTransactionStoreState.mockReturnValue(defaultState);
const { waitForNextUpdate } = render([mockedOrderBusEvent]);
waitForNextUpdate();
await waitForNextTick();
expect(updateOrder).toHaveBeenCalledWith(orderBusEvent);
await act(async () => {
waitForNextUpdate();
await waitForNextTick();
expect(updateOrder).toHaveBeenCalledWith(orderBusEvent);
});
});
it('updates transaction on TransactionResultBusEvents', async () => {
mockTransactionStoreState.mockReturnValue(defaultState);
const { waitForNextUpdate } = render([mockedTransactionResultBusEvent]);
waitForNextUpdate();
await waitForNextTick();
expect(updateTransactionResult).toHaveBeenCalledWith(
transactionResultBusEvent
);
await act(async () => {
waitForNextUpdate();
await waitForNextTick();
expect(updateTransactionResult).toHaveBeenCalledWith(
transactionResultBusEvent
);
});
});
it('updates withdrawal on WithdrawalBusEvents', async () => {
@ -215,11 +220,13 @@ describe('useVegaTransactionManager', () => {
erc20WithdrawalApproval
);
const { waitForNextUpdate } = render([mockedWithdrawalBusEvent]);
waitForNextUpdate();
await waitForNextTick();
expect(updateWithdrawal).toHaveBeenCalledWith(
withdrawalBusEvent,
erc20WithdrawalApproval
);
await act(async () => {
waitForNextUpdate();
await waitForNextTick();
expect(updateWithdrawal).toHaveBeenCalledWith(
withdrawalBusEvent,
erc20WithdrawalApproval
);
});
});
});

View File

@ -1,4 +1,4 @@
import { act } from 'react-dom/test-utils';
import { act } from '@testing-library/react';
const zu = jest.requireActual('zustand'); // if using jest
// a variable to hold reset functions for all stores declared in the app
@ -6,7 +6,14 @@ const storeResetFns = new Set();
// when creating a store, we get its initial state, create a reset function and add it in the set
export const create = (createState) => {
const store = zu.create(createState);
let store;
if (typeof createState === 'function') {
store = zu.create(createState);
} else {
store = (selector, equalityFn) =>
zu.useStore(createState, selector, equalityFn);
Object.assign(store, createState);
}
const initialState = store.getState();
storeResetFns.add(() => store.setState(initialState, true));
return store;

View File

@ -1,4 +1,11 @@
import { fireEvent, render, screen } from '@testing-library/react';
import {
fireEvent,
render,
screen,
act,
waitFor,
} from '@testing-library/react';
import type { RenderResult } from '@testing-library/react';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import { Web3Container } from './web3-container';
@ -63,103 +70,111 @@ jest.mock('@web3-react/core', () => {
};
});
function setup(mock = networkParamsQueryMock) {
return render(
<EnvironmentProvider definitions={mockEnvironment}>
<MockedProvider mocks={[mock]}>
<Web3Container>
<div>
<div>Child</div>
<div>{mockEthereumConfig.collateral_bridge_contract.address}</div>
</div>
</Web3Container>
</MockedProvider>
<Web3ConnectUncontrolledDialog />
</EnvironmentProvider>
);
let renderResults: RenderResult;
async function setup(mock = networkParamsQueryMock) {
await act(async () => {
renderResults = await render(
<EnvironmentProvider definitions={mockEnvironment}>
<MockedProvider mocks={[mock]}>
<Web3Container>
<div>
<div>Child</div>
<div>{mockEthereumConfig.collateral_bridge_contract.address}</div>
</div>
</Web3Container>
</MockedProvider>
<Web3ConnectUncontrolledDialog />
</EnvironmentProvider>
);
});
return renderResults;
}
it('Prompt to connect opens dialog', async () => {
mockHookValue = defaultHookValue;
setup();
describe('Web3Container', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('Prompt to connect opens dialog', async () => {
mockHookValue = defaultHookValue;
await setup();
await waitFor(async () => {
expect(
await screen.findByText('Connect your Ethereum wallet')
).toBeInTheDocument();
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(
await screen.findByText('Connect your Ethereum wallet')
).toBeInTheDocument();
expect(screen.queryByText('Child')).not.toBeInTheDocument();
expect(
screen.queryByTestId('web3-connector-list')
).not.toBeInTheDocument();
await act(() => {
fireEvent.click(screen.getByText('Connect'));
});
expect(screen.getByTestId('web3-connector-list')).toBeInTheDocument();
});
});
expect(screen.queryByText('Child')).not.toBeInTheDocument();
expect(screen.queryByTestId('web3-connector-list')).not.toBeInTheDocument();
it('Error message is shown', async () => {
const message = 'Opps! An error';
mockHookValue = { ...defaultHookValue, error: new Error(message) };
await setup();
fireEvent.click(screen.getByText('Connect'));
expect(screen.getByTestId('web3-connector-list')).toBeInTheDocument();
});
await waitFor(async () => {
expect(
await screen.findByText(`Something went wrong: ${message}`)
).toBeInTheDocument();
expect(screen.queryByText('Child')).not.toBeInTheDocument();
});
});
it('Error message is shown', async () => {
const message = 'Opps! An error';
mockHookValue = { ...defaultHookValue, error: new Error(message) };
setup();
it('Checks that chain ID matches app ID', async () => {
const expectedChainId = 4;
mockHookValue = {
...defaultHookValue,
isActive: true,
chainId: expectedChainId,
};
await setup();
expect(
await screen.findByText(`This app only works on Sepolia`)
).toBeInTheDocument();
expect(screen.queryByText('Child')).not.toBeInTheDocument();
});
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(
await screen.findByText(`Something went wrong: ${message}`)
).toBeInTheDocument();
expect(screen.queryByText('Child')).not.toBeInTheDocument();
});
it('Passes ethereum config to children', async () => {
mockHookValue = {
...defaultHookValue,
isActive: true,
};
await setup();
expect(
await screen.findByText(
mockEthereumConfig.collateral_bridge_contract.address
)
).toBeInTheDocument();
});
it('Checks that chain ID matches app ID', async () => {
const expectedChainId = 4;
mockHookValue = {
...defaultHookValue,
isActive: true,
chainId: expectedChainId,
};
setup();
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(
await screen.findByText(`This app only works on Sepolia`)
).toBeInTheDocument();
expect(screen.queryByText('Child')).not.toBeInTheDocument();
});
it('Passes ethereum config to children', async () => {
mockHookValue = {
...defaultHookValue,
isActive: true,
};
setup();
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(
await screen.findByText(
mockEthereumConfig.collateral_bridge_contract.address
)
).toBeInTheDocument();
});
it('Shows no config found message if the network parameter doesnt exist', async () => {
const mock: MockedResponse<NetworkParamsQuery> = {
request: {
query: NetworkParamsDocument,
},
result: {
data: {
networkParametersConnection: {
edges: [
{
node: {
__typename: 'NetworkParameter',
key: 'nope',
value: 'foo',
it('Shows no config found message if the network parameter doesnt exist', async () => {
const mock: MockedResponse<NetworkParamsQuery> = {
request: {
query: NetworkParamsDocument,
},
result: {
data: {
networkParametersConnection: {
edges: [
{
node: {
__typename: 'NetworkParameter',
key: 'nope',
value: 'foo',
},
},
},
],
],
},
},
},
},
};
setup(mock);
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(await screen.findByText('No data')).toBeInTheDocument();
};
await setup(mock);
expect(await screen.findByText('No data')).toBeInTheDocument();
});
});

View File

@ -1,4 +1,4 @@
import { render, screen } from '@testing-library/react';
import { render, screen, act, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/client/testing';
import type { Account } from '@vegaprotocol/accounts';
import { WithdrawFormContainer } from './withdraw-form-container';
@ -95,7 +95,7 @@ describe('WithdrawFormContainer', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('should be properly rendered', () => {
it('should be properly rendered', async () => {
mockData = [
{ ...account1 },
{ ...account2 },
@ -186,50 +186,68 @@ describe('WithdrawFormContainer', () => {
__typename: 'AccountBalance',
},
];
const { container } = render(
<MockedProvider>
<WithdrawFormContainer {...props} />
</MockedProvider>
);
expect(screen.getByTestId('select-asset')).toBeInTheDocument();
const options = container.querySelectorAll('select[name="asset"] option');
expect(options).toHaveLength(3);
let rendererContainer: Element;
await act(() => {
const { container } = render(<WithdrawFormContainer {...props} />, {
wrapper: MockedProvider,
});
rendererContainer = container;
});
await expect(screen.getByTestId('select-asset')).toBeInTheDocument();
await waitFor(() => {
const options = rendererContainer.querySelectorAll(
'select[name="asset"] option'
);
expect(options).toHaveLength(3);
});
});
it('should display no data message', () => {
it('should display no data message', async () => {
mockData = null;
render(
<MockedProvider>
<WithdrawFormContainer {...props} />
</MockedProvider>
);
await act(() => {
render(
<MockedProvider>
<WithdrawFormContainer {...props} />
</MockedProvider>
);
});
expect(
screen.getByText('You have no assets to withdraw')
).toBeInTheDocument();
});
it('should filter out zero balance account assets', () => {
it('should filter out zero balance account assets', async () => {
let rendererContainer: Element;
mockData = [{ ...account1 }, { ...account2, balance: '0' }];
const { container } = render(
<MockedProvider>
<WithdrawFormContainer {...props} />
</MockedProvider>
);
await act(() => {
const { container } = render(
<MockedProvider>
<WithdrawFormContainer {...props} />
</MockedProvider>
);
rendererContainer = container;
});
expect(screen.getByTestId('select-asset')).toBeInTheDocument();
const options = container.querySelectorAll('select[name="asset"] option');
expect(options).toHaveLength(2);
await waitFor(() => {
const options = rendererContainer.querySelectorAll(
'select[name="asset"] option'
);
expect(options).toHaveLength(2);
});
});
it('when no accounts have a balance should should display no data message', () => {
it('when no accounts have a balance should should display no data message', async () => {
mockData = [
{ ...account1, balance: '0' },
{ ...account2, balance: '0' },
];
render(
<MockedProvider>
<WithdrawFormContainer {...props} />
</MockedProvider>
);
await act(() => {
render(
<MockedProvider>
<WithdrawFormContainer {...props} />
</MockedProvider>
);
});
expect(
screen.getByText('You have no assets to withdraw')
).toBeInTheDocument();

View File

@ -23,13 +23,17 @@ export const WithdrawFormContainer = ({
variables,
});
const filteredAsset = data
?.filter(
(account) =>
account.type === Types.AccountType.ACCOUNT_TYPE_GENERAL &&
toBigNum(account.balance, account.asset.decimals).isGreaterThan(0)
)
.map((account) => account.asset);
const filteredAsset = useMemo(
() =>
data
?.filter(
(account) =>
account.type === Types.AccountType.ACCOUNT_TYPE_GENERAL &&
toBigNum(account.balance, account.asset.decimals).isGreaterThan(0)
)
.map((account) => account.asset),
[data]
);
const assets = filteredAsset?.length ? filteredAsset : null;
return (
<AsyncRenderer

View File

@ -92,9 +92,6 @@ export const WithdrawForm = ({
}: {
field: ControllerRenderProps<FormFields, 'asset'>;
}) => {
console.log('assets', assets.filter(isAssetTypeERC20));
console.log('selected asset', selectedAsset);
return (
<RichSelect
data-testid="select-asset"
@ -110,7 +107,7 @@ export const WithdrawForm = ({
hasError={Boolean(errors.asset?.message)}
>
{assets.filter(isAssetTypeERC20).map((a) => (
<AssetOption asset={a} />
<AssetOption key={a.id} asset={a} />
))}
</RichSelect>
);