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

View File

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

View File

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

View File

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

View File

@ -82,8 +82,9 @@ describe('FillsTable', () => {
liquidityFee: '2', liquidityFee: '2',
}, },
}); });
await act(async () => {
render(<FillsTable partyId={partyId} rowData={[{ ...buyerFill }]} />); render(<FillsTable partyId={partyId} rowData={[{ ...buyerFill }]} />);
});
await waitForGridToBeInTheDOM(); await waitForGridToBeInTheDOM();
await waitForDataToHaveLoaded(); await waitForDataToHaveLoaded();
@ -119,8 +120,9 @@ describe('FillsTable', () => {
liquidityFee: '1', liquidityFee: '1',
}, },
}); });
await act(async () => {
render(<FillsTable partyId={partyId} rowData={[buyerFill]} />); render(<FillsTable partyId={partyId} rowData={[buyerFill]} />);
});
await waitForGridToBeInTheDOM(); await waitForGridToBeInTheDOM();
await waitForDataToHaveLoaded(); await waitForDataToHaveLoaded();
@ -150,10 +152,13 @@ describe('FillsTable', () => {
}, },
aggressor: Schema.Side.SIDE_SELL, aggressor: Schema.Side.SIDE_SELL,
}); });
let rerenderer: (ui: React.ReactElement) => void;
await act(async () => {
const { rerender } = render( const { rerender } = render(
<FillsTable partyId={partyId} rowData={[takerFill]} /> <FillsTable partyId={partyId} rowData={[takerFill]} />
); );
rerenderer = rerender;
});
await waitForGridToBeInTheDOM(); await waitForGridToBeInTheDOM();
await waitForDataToHaveLoaded(); await waitForDataToHaveLoaded();
@ -169,8 +174,9 @@ describe('FillsTable', () => {
}, },
aggressor: Schema.Side.SIDE_BUY, aggressor: Schema.Side.SIDE_BUY,
}); });
await act(async () => {
rerender(<FillsTable partyId={partyId} rowData={[makerFill]} />); rerenderer(<FillsTable partyId={partyId} rowData={[makerFill]} />);
});
await waitForGridToBeInTheDOM(); await waitForGridToBeInTheDOM();
await waitForDataToHaveLoaded(); await waitForDataToHaveLoaded();
@ -189,7 +195,7 @@ describe('FillsTable', () => {
}, },
aggressor: Schema.Side.SIDE_SELL, aggressor: Schema.Side.SIDE_SELL,
}); });
act(() => { await act(async () => {
render(<FillsTable partyId={partyId} rowData={[takerFill]} />); render(<FillsTable partyId={partyId} rowData={[takerFill]} />);
}); });
await waitForGridToBeInTheDOM(); await waitForGridToBeInTheDOM();
@ -206,11 +212,12 @@ describe('FillsTable', () => {
await waitFor(() => { await waitFor(() => {
expect(feeCell).toBeInTheDocument(); expect(feeCell).toBeInTheDocument();
}); });
act(() => { await act(async () => {
userEvent.hover(feeCell as HTMLElement); 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(); 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 { OrderListManager } from './order-list-manager';
import * as useDataProviderHook from '@vegaprotocol/react-helpers'; import * as useDataProviderHook from '@vegaprotocol/react-helpers';
import type { OrderFieldsFragment } from '../'; 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({ jest.spyOn(useDataProviderHook, 'useDataProvider').mockReturnValue({
data: [], data: [],
loading: true, loading: true,
@ -29,11 +29,13 @@ it('Renders a loading state while awaiting orders', () => {
load: jest.fn(), load: jest.fn(),
totalCount: 0, totalCount: 0,
}); });
await act(async () => {
render(generateJsx()); render(generateJsx());
});
expect(screen.getByText('Loading...')).toBeInTheDocument(); expect(screen.getByText('Loading...')).toBeInTheDocument();
}); });
it('Renders an error state', () => { it('Renders an error state', async () => {
const errorMsg = 'Oops! An Error'; const errorMsg = 'Oops! An Error';
jest.spyOn(useDataProviderHook, 'useDataProvider').mockReturnValue({ jest.spyOn(useDataProviderHook, 'useDataProvider').mockReturnValue({
data: [], data: [],
@ -44,7 +46,9 @@ it('Renders an error state', () => {
load: jest.fn(), load: jest.fn(),
totalCount: undefined, totalCount: undefined,
}); });
await act(async () => {
render(generateJsx()); render(generateJsx());
});
expect( expect(
screen.getByText(`Something went wrong: ${errorMsg}`) screen.getByText(`Something went wrong: ${errorMsg}`)
).toBeInTheDocument(); ).toBeInTheDocument();
@ -63,6 +67,8 @@ it('Renders the order list if orders provided', async () => {
load: jest.fn(), load: jest.fn(),
totalCount: undefined, totalCount: undefined,
}); });
await act(async () => {
render(generateJsx()); render(generateJsx());
});
expect(await screen.findByText('OrderList')).toBeInTheDocument(); 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 type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing'; import { MockedProvider } from '@apollo/client/testing';
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
@ -33,6 +33,7 @@ const render = (mocks?: MockedResponse[]) => {
const wrapper = ({ children }: { children: ReactNode }) => ( const wrapper = ({ children }: { children: ReactNode }) => (
<MockedProvider mocks={mocks}>{children}</MockedProvider> <MockedProvider mocks={mocks}>{children}</MockedProvider>
); );
return renderHook(() => useVegaTransactionUpdater(), { wrapper }); return renderHook(() => useVegaTransactionUpdater(), { wrapper });
}; };
@ -193,20 +194,24 @@ describe('useVegaTransactionManager', () => {
it('updates order on OrderBusEvents', async () => { it('updates order on OrderBusEvents', async () => {
mockTransactionStoreState.mockReturnValue(defaultState); mockTransactionStoreState.mockReturnValue(defaultState);
const { waitForNextUpdate } = render([mockedOrderBusEvent]); const { waitForNextUpdate } = render([mockedOrderBusEvent]);
await act(async () => {
waitForNextUpdate(); waitForNextUpdate();
await waitForNextTick(); await waitForNextTick();
expect(updateOrder).toHaveBeenCalledWith(orderBusEvent); expect(updateOrder).toHaveBeenCalledWith(orderBusEvent);
}); });
});
it('updates transaction on TransactionResultBusEvents', async () => { it('updates transaction on TransactionResultBusEvents', async () => {
mockTransactionStoreState.mockReturnValue(defaultState); mockTransactionStoreState.mockReturnValue(defaultState);
const { waitForNextUpdate } = render([mockedTransactionResultBusEvent]); const { waitForNextUpdate } = render([mockedTransactionResultBusEvent]);
await act(async () => {
waitForNextUpdate(); waitForNextUpdate();
await waitForNextTick(); await waitForNextTick();
expect(updateTransactionResult).toHaveBeenCalledWith( expect(updateTransactionResult).toHaveBeenCalledWith(
transactionResultBusEvent transactionResultBusEvent
); );
}); });
});
it('updates withdrawal on WithdrawalBusEvents', async () => { it('updates withdrawal on WithdrawalBusEvents', async () => {
mockTransactionStoreState.mockReturnValue(defaultState); mockTransactionStoreState.mockReturnValue(defaultState);
@ -215,6 +220,7 @@ describe('useVegaTransactionManager', () => {
erc20WithdrawalApproval erc20WithdrawalApproval
); );
const { waitForNextUpdate } = render([mockedWithdrawalBusEvent]); const { waitForNextUpdate } = render([mockedWithdrawalBusEvent]);
await act(async () => {
waitForNextUpdate(); waitForNextUpdate();
await waitForNextTick(); await waitForNextTick();
expect(updateWithdrawal).toHaveBeenCalledWith( expect(updateWithdrawal).toHaveBeenCalledWith(
@ -222,4 +228,5 @@ describe('useVegaTransactionManager', () => {
erc20WithdrawalApproval 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 const zu = jest.requireActual('zustand'); // if using jest
// a variable to hold reset functions for all stores declared in the app // 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 // when creating a store, we get its initial state, create a reset function and add it in the set
export const create = (createState) => { 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(); const initialState = store.getState();
storeResetFns.add(() => store.setState(initialState, true)); storeResetFns.add(() => store.setState(initialState, true));
return store; 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 type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing'; import { MockedProvider } from '@apollo/client/testing';
import { Web3Container } from './web3-container'; import { Web3Container } from './web3-container';
@ -63,8 +70,10 @@ jest.mock('@web3-react/core', () => {
}; };
}); });
function setup(mock = networkParamsQueryMock) { let renderResults: RenderResult;
return render( async function setup(mock = networkParamsQueryMock) {
await act(async () => {
renderResults = await render(
<EnvironmentProvider definitions={mockEnvironment}> <EnvironmentProvider definitions={mockEnvironment}>
<MockedProvider mocks={[mock]}> <MockedProvider mocks={[mock]}>
<Web3Container> <Web3Container>
@ -77,68 +86,74 @@ function setup(mock = networkParamsQueryMock) {
<Web3ConnectUncontrolledDialog /> <Web3ConnectUncontrolledDialog />
</EnvironmentProvider> </EnvironmentProvider>
); );
});
return renderResults;
} }
it('Prompt to connect opens dialog', async () => { describe('Web3Container', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('Prompt to connect opens dialog', async () => {
mockHookValue = defaultHookValue; mockHookValue = defaultHookValue;
setup(); await setup();
await waitFor(async () => {
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect( expect(
await screen.findByText('Connect your Ethereum wallet') await screen.findByText('Connect your Ethereum wallet')
).toBeInTheDocument(); ).toBeInTheDocument();
expect(screen.queryByText('Child')).not.toBeInTheDocument(); expect(screen.queryByText('Child')).not.toBeInTheDocument();
expect(screen.queryByTestId('web3-connector-list')).not.toBeInTheDocument(); expect(
screen.queryByTestId('web3-connector-list')
).not.toBeInTheDocument();
await act(() => {
fireEvent.click(screen.getByText('Connect')); fireEvent.click(screen.getByText('Connect'));
});
expect(screen.getByTestId('web3-connector-list')).toBeInTheDocument(); expect(screen.getByTestId('web3-connector-list')).toBeInTheDocument();
}); });
});
it('Error message is shown', async () => { it('Error message is shown', async () => {
const message = 'Opps! An error'; const message = 'Opps! An error';
mockHookValue = { ...defaultHookValue, error: new Error(message) }; mockHookValue = { ...defaultHookValue, error: new Error(message) };
setup(); await setup();
expect(screen.getByText('Loading...')).toBeInTheDocument(); await waitFor(async () => {
expect( expect(
await screen.findByText(`Something went wrong: ${message}`) await screen.findByText(`Something went wrong: ${message}`)
).toBeInTheDocument(); ).toBeInTheDocument();
expect(screen.queryByText('Child')).not.toBeInTheDocument(); expect(screen.queryByText('Child')).not.toBeInTheDocument();
}); });
});
it('Checks that chain ID matches app ID', async () => { it('Checks that chain ID matches app ID', async () => {
const expectedChainId = 4; const expectedChainId = 4;
mockHookValue = { mockHookValue = {
...defaultHookValue, ...defaultHookValue,
isActive: true, isActive: true,
chainId: expectedChainId, chainId: expectedChainId,
}; };
setup(); await setup();
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect( expect(
await screen.findByText(`This app only works on Sepolia`) await screen.findByText(`This app only works on Sepolia`)
).toBeInTheDocument(); ).toBeInTheDocument();
expect(screen.queryByText('Child')).not.toBeInTheDocument(); expect(screen.queryByText('Child')).not.toBeInTheDocument();
}); });
it('Passes ethereum config to children', async () => { it('Passes ethereum config to children', async () => {
mockHookValue = { mockHookValue = {
...defaultHookValue, ...defaultHookValue,
isActive: true, isActive: true,
}; };
setup(); await setup();
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect( expect(
await screen.findByText( await screen.findByText(
mockEthereumConfig.collateral_bridge_contract.address mockEthereumConfig.collateral_bridge_contract.address
) )
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it('Shows no config found message if the network parameter doesnt exist', async () => { it('Shows no config found message if the network parameter doesnt exist', async () => {
const mock: MockedResponse<NetworkParamsQuery> = { const mock: MockedResponse<NetworkParamsQuery> = {
request: { request: {
query: NetworkParamsDocument, query: NetworkParamsDocument,
@ -159,7 +174,7 @@ it('Shows no config found message if the network parameter doesnt exist', async
}, },
}, },
}; };
setup(mock); await setup(mock);
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(await screen.findByText('No data')).toBeInTheDocument(); 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 { MockedProvider } from '@apollo/client/testing';
import type { Account } from '@vegaprotocol/accounts'; import type { Account } from '@vegaprotocol/accounts';
import { WithdrawFormContainer } from './withdraw-form-container'; import { WithdrawFormContainer } from './withdraw-form-container';
@ -95,7 +95,7 @@ describe('WithdrawFormContainer', () => {
afterEach(() => { afterEach(() => {
jest.resetAllMocks(); jest.resetAllMocks();
}); });
it('should be properly rendered', () => { it('should be properly rendered', async () => {
mockData = [ mockData = [
{ ...account1 }, { ...account1 },
{ ...account2 }, { ...account2 },
@ -186,50 +186,68 @@ describe('WithdrawFormContainer', () => {
__typename: 'AccountBalance', __typename: 'AccountBalance',
}, },
]; ];
const { container } = render( let rendererContainer: Element;
<MockedProvider> await act(() => {
<WithdrawFormContainer {...props} /> const { container } = render(<WithdrawFormContainer {...props} />, {
</MockedProvider> wrapper: MockedProvider,
});
rendererContainer = container;
});
await expect(screen.getByTestId('select-asset')).toBeInTheDocument();
await waitFor(() => {
const options = rendererContainer.querySelectorAll(
'select[name="asset"] option'
); );
expect(screen.getByTestId('select-asset')).toBeInTheDocument();
const options = container.querySelectorAll('select[name="asset"] option');
expect(options).toHaveLength(3); expect(options).toHaveLength(3);
}); });
});
it('should display no data message', () => { it('should display no data message', async () => {
mockData = null; mockData = null;
await act(() => {
render( render(
<MockedProvider> <MockedProvider>
<WithdrawFormContainer {...props} /> <WithdrawFormContainer {...props} />
</MockedProvider> </MockedProvider>
); );
});
expect( expect(
screen.getByText('You have no assets to withdraw') screen.getByText('You have no assets to withdraw')
).toBeInTheDocument(); ).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' }]; mockData = [{ ...account1 }, { ...account2, balance: '0' }];
await act(() => {
const { container } = render( const { container } = render(
<MockedProvider> <MockedProvider>
<WithdrawFormContainer {...props} /> <WithdrawFormContainer {...props} />
</MockedProvider> </MockedProvider>
); );
rendererContainer = container;
});
expect(screen.getByTestId('select-asset')).toBeInTheDocument(); expect(screen.getByTestId('select-asset')).toBeInTheDocument();
const options = container.querySelectorAll('select[name="asset"] option'); await waitFor(() => {
const options = rendererContainer.querySelectorAll(
'select[name="asset"] option'
);
expect(options).toHaveLength(2); 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 = [ mockData = [
{ ...account1, balance: '0' }, { ...account1, balance: '0' },
{ ...account2, balance: '0' }, { ...account2, balance: '0' },
]; ];
await act(() => {
render( render(
<MockedProvider> <MockedProvider>
<WithdrawFormContainer {...props} /> <WithdrawFormContainer {...props} />
</MockedProvider> </MockedProvider>
); );
});
expect( expect(
screen.getByText('You have no assets to withdraw') screen.getByText('You have no assets to withdraw')
).toBeInTheDocument(); ).toBeInTheDocument();

View File

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

View File

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