Testing library update to 14.4.3 (#2741)

* Update RTL to v14.4.3

* fixed test cases QueryForm.spec.tsx, SchemaVersion.spec.tsx

Co-authored-by: Oleg Shur <workshur@gmail.com>
Co-authored-by: davitbejanyan <dbejanyan@provectus.com>
This commit is contained in:
David 2022-10-26 23:15:25 +04:00 committed by GitHub
parent e67d940981
commit b43ba68405
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
55 changed files with 612 additions and 626 deletions

View file

@ -82,7 +82,7 @@
"@openapitools/openapi-generator-cli": "^2.5.1", "@openapitools/openapi-generator-cli": "^2.5.1",
"@testing-library/dom": "^8.11.1", "@testing-library/dom": "^8.11.1",
"@testing-library/jest-dom": "^5.16.4", "@testing-library/jest-dom": "^5.16.4",
"@testing-library/user-event": "^13.5.0", "@testing-library/user-event": "^14.4.3",
"@types/eventsource": "^1.1.8", "@types/eventsource": "^1.1.8",
"@types/jest": "^29.0.1", "@types/jest": "^29.0.1",
"@types/lodash": "^4.14.172", "@types/lodash": "^4.14.172",

View file

@ -19,7 +19,7 @@ specifiers:
'@testing-library/dom': ^8.11.1 '@testing-library/dom': ^8.11.1
'@testing-library/jest-dom': ^5.16.4 '@testing-library/jest-dom': ^5.16.4
'@testing-library/react': ^13.2.0 '@testing-library/react': ^13.2.0
'@testing-library/user-event': ^13.5.0 '@testing-library/user-event': ^14.4.3
'@types/eventsource': ^1.1.8 '@types/eventsource': ^1.1.8
'@types/jest': ^29.0.1 '@types/jest': ^29.0.1
'@types/lodash': ^4.14.172 '@types/lodash': ^4.14.172
@ -144,7 +144,7 @@ devDependencies:
'@openapitools/openapi-generator-cli': 2.5.1 '@openapitools/openapi-generator-cli': 2.5.1
'@testing-library/dom': 8.13.0 '@testing-library/dom': 8.13.0
'@testing-library/jest-dom': 5.16.4 '@testing-library/jest-dom': 5.16.4
'@testing-library/user-event': 13.5.0_tlwynutqiyp5mns3woioasuxnq '@testing-library/user-event': 14.4.3_tlwynutqiyp5mns3woioasuxnq
'@types/eventsource': 1.1.8 '@types/eventsource': 1.1.8
'@types/jest': 29.0.1 '@types/jest': 29.0.1
'@types/lodash': 4.14.177 '@types/lodash': 4.14.177
@ -3337,13 +3337,12 @@ packages:
react-dom: 18.1.0_react@18.1.0 react-dom: 18.1.0_react@18.1.0
dev: false dev: false
/@testing-library/user-event/13.5.0_tlwynutqiyp5mns3woioasuxnq: /@testing-library/user-event/14.4.3_tlwynutqiyp5mns3woioasuxnq:
resolution: {integrity: sha512-5Kwtbo3Y/NowpkbRuSepbyMFkZmHgD+vPzYB/RJ4oxt5Gj/avFFBYjhw27cqSVPVw/3a67NK1PbiIr9k4Gwmdg==} resolution: {integrity: sha512-kCUc5MEwaEMakkO5x7aoD+DLi02ehmEM2QCGWvNqAS1dV/fAvORWEjnjsEIvml59M7Y5kCkWN6fCCyPOe8OL6Q==}
engines: {node: '>=10', npm: '>=6'} engines: {node: '>=12', npm: '>=6'}
peerDependencies: peerDependencies:
'@testing-library/dom': '>=7.21.4' '@testing-library/dom': '>=7.21.4'
dependencies: dependencies:
'@babel/runtime': 7.17.9
'@testing-library/dom': 8.13.0 '@testing-library/dom': 8.13.0
dev: true dev: true

View file

@ -2,7 +2,6 @@ import React from 'react';
import { render, WithRoute } from 'lib/testHelpers'; import { render, WithRoute } from 'lib/testHelpers';
import { screen } from '@testing-library/dom'; import { screen } from '@testing-library/dom';
import { clusterBrokerPath } from 'lib/paths'; import { clusterBrokerPath } from 'lib/paths';
import { act } from '@testing-library/react';
import { brokerLogDirsPayload } from 'lib/fixtures/brokers'; import { brokerLogDirsPayload } from 'lib/fixtures/brokers';
import { useBrokerLogDirs } from 'lib/hooks/api/brokers'; import { useBrokerLogDirs } from 'lib/hooks/api/brokers';
import { BrokerLogdirs } from 'generated-sources'; import { BrokerLogdirs } from 'generated-sources';
@ -20,16 +19,14 @@ describe('BrokerLogdir Component', () => {
(useBrokerLogDirs as jest.Mock).mockImplementation(() => ({ (useBrokerLogDirs as jest.Mock).mockImplementation(() => ({
data: payload, data: payload,
})); }));
await act(() => { await render(
render( <WithRoute path={clusterBrokerPath()}>
<WithRoute path={clusterBrokerPath()}> <BrokerLogdir />
<BrokerLogdir /> </WithRoute>,
</WithRoute>, {
{ initialEntries: [clusterBrokerPath(clusterName, brokerId)],
initialEntries: [clusterBrokerPath(clusterName, brokerId)], }
} );
);
});
}; };
it('shows warning when server returns undefined logDirs response', async () => { it('shows warning when server returns undefined logDirs response', async () => {

View file

@ -6,7 +6,6 @@ import { useBrokerConfig } from 'lib/hooks/api/brokers';
import { brokerConfigPayload } from 'lib/fixtures/brokers'; import { brokerConfigPayload } from 'lib/fixtures/brokers';
import Configs from 'components/Brokers/Broker/Configs/Configs'; import Configs from 'components/Brokers/Broker/Configs/Configs';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { act } from '@testing-library/react';
const clusterName = 'Cluster_Name'; const clusterName = 'Cluster_Name';
const brokerId = 'Broker_Id'; const brokerId = 'Broker_Id';
@ -42,9 +41,7 @@ describe('Configs', () => {
}); });
it('updates textbox value', async () => { it('updates textbox value', async () => {
await act(() => { await userEvent.click(screen.getAllByLabelText('editAction')[0]);
userEvent.click(screen.getAllByLabelText('editAction')[0]);
});
const textbox = screen.getByLabelText('inputValue'); const textbox = screen.getByLabelText('inputValue');
expect(textbox).toBeInTheDocument(); expect(textbox).toBeInTheDocument();
@ -59,9 +56,9 @@ describe('Configs', () => {
screen.getByRole('button', { name: 'cancelAction' }) screen.getByRole('button', { name: 'cancelAction' })
).toBeInTheDocument(); ).toBeInTheDocument();
await act(() => { await userEvent.click(
userEvent.click(screen.getByRole('button', { name: 'confirmAction' })); screen.getByRole('button', { name: 'confirmAction' })
}); );
expect( expect(
screen.getByText('Are you sure you want to change the value?') screen.getByText('Are you sure you want to change the value?')

View file

@ -2,7 +2,6 @@ import React from 'react';
import { render, WithRoute } from 'lib/testHelpers'; import { render, WithRoute } from 'lib/testHelpers';
import { screen, waitFor } from '@testing-library/dom'; import { screen, waitFor } from '@testing-library/dom';
import { clusterBrokerPath, clusterBrokersPath } from 'lib/paths'; import { clusterBrokerPath, clusterBrokersPath } from 'lib/paths';
import { act } from '@testing-library/react';
import BrokersList from 'components/Brokers/BrokersList/BrokersList'; import BrokersList from 'components/Brokers/BrokersList/BrokersList';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { useBrokers } from 'lib/hooks/api/brokers'; import { useBrokers } from 'lib/hooks/api/brokers';
@ -57,9 +56,8 @@ describe('BrokersList Component', () => {
}); });
it('opens broker when row clicked', async () => { it('opens broker when row clicked', async () => {
renderComponent(); renderComponent();
await act(() => { await userEvent.click(screen.getByRole('cell', { name: '0' }));
userEvent.click(screen.getByRole('cell', { name: '0' }));
});
await waitFor(() => await waitFor(() =>
expect(mockedUsedNavigate).toBeCalledWith( expect(mockedUsedNavigate).toBeCalledWith(
clusterBrokerPath(clusterName, '0') clusterBrokerPath(clusterName, '0')

View file

@ -13,7 +13,6 @@ import {
clusterSchemasPath, clusterSchemasPath,
clusterTopicsPath, clusterTopicsPath,
} from 'lib/paths'; } from 'lib/paths';
import { act } from 'react-dom/test-utils';
import { useClusters } from 'lib/hooks/api/clusters'; import { useClusters } from 'lib/hooks/api/clusters';
import { onlineClusterPayload } from 'lib/fixtures/clusters'; import { onlineClusterPayload } from 'lib/fixtures/clusters';
@ -54,14 +53,12 @@ describe('Cluster', () => {
(useClusters as jest.Mock).mockImplementation(() => ({ (useClusters as jest.Mock).mockImplementation(() => ({
data: payload, data: payload,
})); }));
await act(() => { await render(
render( <WithRoute path={`${clusterPath()}/*`}>
<WithRoute path={`${clusterPath()}/*`}> <ClusterComponent />
<ClusterComponent /> </WithRoute>,
</WithRoute>, { initialEntries: [pathname] }
{ initialEntries: [pathname] } );
);
});
}; };
it('renders Brokers', async () => { it('renders Brokers', async () => {

View file

@ -33,10 +33,10 @@ const expectActionButtonsExists = () => {
expect(screen.getByText('Restart Failed Tasks')).toBeInTheDocument(); expect(screen.getByText('Restart Failed Tasks')).toBeInTheDocument();
expect(screen.getByText('Delete')).toBeInTheDocument(); expect(screen.getByText('Delete')).toBeInTheDocument();
}; };
const afterClickDropDownButton = () => { const afterClickDropDownButton = async () => {
const dropDownButton = screen.getAllByRole('button'); const dropDownButton = screen.getAllByRole('button');
expect(dropDownButton.length).toEqual(1); expect(dropDownButton.length).toEqual(1);
userEvent.click(dropDownButton[0]); await userEvent.click(dropDownButton[0]);
}; };
describe('Actions', () => { describe('Actions', () => {
afterEach(() => { afterEach(() => {
@ -61,48 +61,48 @@ describe('Actions', () => {
{ initialEntries: [path] } { initialEntries: [path] }
); );
it('renders buttons when paused', () => { it('renders buttons when paused', async () => {
(useConnector as jest.Mock).mockImplementation(() => ({ (useConnector as jest.Mock).mockImplementation(() => ({
data: set({ ...connector }, 'status.state', ConnectorState.PAUSED), data: set({ ...connector }, 'status.state', ConnectorState.PAUSED),
})); }));
renderComponent(); renderComponent();
afterClickDropDownButton(); await afterClickDropDownButton();
expect(screen.getAllByRole('menuitem').length).toEqual(5); expect(screen.getAllByRole('menuitem').length).toEqual(5);
expect(screen.getByText('Resume')).toBeInTheDocument(); expect(screen.getByText('Resume')).toBeInTheDocument();
expect(screen.queryByText('Pause')).not.toBeInTheDocument(); expect(screen.queryByText('Pause')).not.toBeInTheDocument();
expectActionButtonsExists(); expectActionButtonsExists();
}); });
it('renders buttons when failed', () => { it('renders buttons when failed', async () => {
(useConnector as jest.Mock).mockImplementation(() => ({ (useConnector as jest.Mock).mockImplementation(() => ({
data: set({ ...connector }, 'status.state', ConnectorState.FAILED), data: set({ ...connector }, 'status.state', ConnectorState.FAILED),
})); }));
renderComponent(); renderComponent();
afterClickDropDownButton(); await afterClickDropDownButton();
expect(screen.getAllByRole('menuitem').length).toEqual(4); expect(screen.getAllByRole('menuitem').length).toEqual(4);
expect(screen.queryByText('Resume')).not.toBeInTheDocument(); expect(screen.queryByText('Resume')).not.toBeInTheDocument();
expect(screen.queryByText('Pause')).not.toBeInTheDocument(); expect(screen.queryByText('Pause')).not.toBeInTheDocument();
expectActionButtonsExists(); expectActionButtonsExists();
}); });
it('renders buttons when unassigned', () => { it('renders buttons when unassigned', async () => {
(useConnector as jest.Mock).mockImplementation(() => ({ (useConnector as jest.Mock).mockImplementation(() => ({
data: set({ ...connector }, 'status.state', ConnectorState.UNASSIGNED), data: set({ ...connector }, 'status.state', ConnectorState.UNASSIGNED),
})); }));
renderComponent(); renderComponent();
afterClickDropDownButton(); await afterClickDropDownButton();
expect(screen.getAllByRole('menuitem').length).toEqual(4); expect(screen.getAllByRole('menuitem').length).toEqual(4);
expect(screen.queryByText('Resume')).not.toBeInTheDocument(); expect(screen.queryByText('Resume')).not.toBeInTheDocument();
expect(screen.queryByText('Pause')).not.toBeInTheDocument(); expect(screen.queryByText('Pause')).not.toBeInTheDocument();
expectActionButtonsExists(); expectActionButtonsExists();
}); });
it('renders buttons when running connector action', () => { it('renders buttons when running connector action', async () => {
(useConnector as jest.Mock).mockImplementation(() => ({ (useConnector as jest.Mock).mockImplementation(() => ({
data: set({ ...connector }, 'status.state', ConnectorState.RUNNING), data: set({ ...connector }, 'status.state', ConnectorState.RUNNING),
})); }));
renderComponent(); renderComponent();
afterClickDropDownButton(); await afterClickDropDownButton();
expect(screen.getAllByRole('menuitem').length).toEqual(5); expect(screen.getAllByRole('menuitem').length).toEqual(5);
expect(screen.queryByText('Resume')).not.toBeInTheDocument(); expect(screen.queryByText('Resume')).not.toBeInTheDocument();
expect(screen.getByText('Pause')).toBeInTheDocument(); expect(screen.getByText('Pause')).toBeInTheDocument();
@ -118,34 +118,34 @@ describe('Actions', () => {
it('opens confirmation modal when delete button clicked', async () => { it('opens confirmation modal when delete button clicked', async () => {
renderComponent(); renderComponent();
afterClickDropDownButton(); await afterClickDropDownButton();
await waitFor(() => await waitFor(async () =>
userEvent.click(screen.getByRole('menuitem', { name: 'Delete' })) userEvent.click(screen.getByRole('menuitem', { name: 'Delete' }))
); );
expect(screen.getByRole('dialog')).toBeInTheDocument(); expect(screen.getByRole('dialog')).toBeInTheDocument();
}); });
it('calls restartConnector when restart button clicked', () => { it('calls restartConnector when restart button clicked', async () => {
const restartConnector = jest.fn(); const restartConnector = jest.fn();
(useUpdateConnectorState as jest.Mock).mockImplementation(() => ({ (useUpdateConnectorState as jest.Mock).mockImplementation(() => ({
mutateAsync: restartConnector, mutateAsync: restartConnector,
})); }));
renderComponent(); renderComponent();
afterClickDropDownButton(); await afterClickDropDownButton();
userEvent.click( await userEvent.click(
screen.getByRole('menuitem', { name: 'Restart Connector' }) screen.getByRole('menuitem', { name: 'Restart Connector' })
); );
expect(restartConnector).toHaveBeenCalledWith(ConnectorAction.RESTART); expect(restartConnector).toHaveBeenCalledWith(ConnectorAction.RESTART);
}); });
it('calls restartAllTasks', () => { it('calls restartAllTasks', async () => {
const restartAllTasks = jest.fn(); const restartAllTasks = jest.fn();
(useUpdateConnectorState as jest.Mock).mockImplementation(() => ({ (useUpdateConnectorState as jest.Mock).mockImplementation(() => ({
mutateAsync: restartAllTasks, mutateAsync: restartAllTasks,
})); }));
renderComponent(); renderComponent();
afterClickDropDownButton(); await afterClickDropDownButton();
userEvent.click( await userEvent.click(
screen.getByRole('menuitem', { name: 'Restart All Tasks' }) screen.getByRole('menuitem', { name: 'Restart All Tasks' })
); );
expect(restartAllTasks).toHaveBeenCalledWith( expect(restartAllTasks).toHaveBeenCalledWith(
@ -153,14 +153,14 @@ describe('Actions', () => {
); );
}); });
it('calls restartFailedTasks', () => { it('calls restartFailedTasks', async () => {
const restartFailedTasks = jest.fn(); const restartFailedTasks = jest.fn();
(useUpdateConnectorState as jest.Mock).mockImplementation(() => ({ (useUpdateConnectorState as jest.Mock).mockImplementation(() => ({
mutateAsync: restartFailedTasks, mutateAsync: restartFailedTasks,
})); }));
renderComponent(); renderComponent();
afterClickDropDownButton(); await afterClickDropDownButton();
userEvent.click( await userEvent.click(
screen.getByRole('menuitem', { name: 'Restart Failed Tasks' }) screen.getByRole('menuitem', { name: 'Restart Failed Tasks' })
); );
expect(restartFailedTasks).toHaveBeenCalledWith( expect(restartFailedTasks).toHaveBeenCalledWith(
@ -168,18 +168,18 @@ describe('Actions', () => {
); );
}); });
it('calls pauseConnector when pause button clicked', () => { it('calls pauseConnector when pause button clicked', async () => {
const pauseConnector = jest.fn(); const pauseConnector = jest.fn();
(useUpdateConnectorState as jest.Mock).mockImplementation(() => ({ (useUpdateConnectorState as jest.Mock).mockImplementation(() => ({
mutateAsync: pauseConnector, mutateAsync: pauseConnector,
})); }));
renderComponent(); renderComponent();
afterClickDropDownButton(); await afterClickDropDownButton();
userEvent.click(screen.getByRole('menuitem', { name: 'Pause' })); await userEvent.click(screen.getByRole('menuitem', { name: 'Pause' }));
expect(pauseConnector).toHaveBeenCalledWith(ConnectorAction.PAUSE); expect(pauseConnector).toHaveBeenCalledWith(ConnectorAction.PAUSE);
}); });
it('calls resumeConnector when resume button clicked', () => { it('calls resumeConnector when resume button clicked', async () => {
const resumeConnector = jest.fn(); const resumeConnector = jest.fn();
(useConnector as jest.Mock).mockImplementation(() => ({ (useConnector as jest.Mock).mockImplementation(() => ({
data: set({ ...connector }, 'status.state', ConnectorState.PAUSED), data: set({ ...connector }, 'status.state', ConnectorState.PAUSED),
@ -188,8 +188,8 @@ describe('Actions', () => {
mutateAsync: resumeConnector, mutateAsync: resumeConnector,
})); }));
renderComponent(); renderComponent();
afterClickDropDownButton(); await afterClickDropDownButton();
userEvent.click(screen.getByRole('menuitem', { name: 'Resume' })); await userEvent.click(screen.getByRole('menuitem', { name: 'Resume' }));
expect(resumeConnector).toHaveBeenCalledWith(ConnectorAction.RESUME); expect(resumeConnector).toHaveBeenCalledWith(ConnectorAction.RESUME);
}); });
}); });

View file

@ -57,7 +57,7 @@ describe('Tasks', () => {
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it('renders truncates long trace and expands', () => { it('renders truncates long trace and expands', async () => {
renderComponent(tasks); renderComponent(tasks);
const trace = tasks[2]?.status?.trace || ''; const trace = tasks[2]?.status?.trace || '';
@ -72,7 +72,7 @@ describe('Tasks', () => {
// Full trace is not visible // Full trace is not visible
expect(expandedDetails).not.toBeInTheDocument(); expect(expandedDetails).not.toBeInTheDocument();
userEvent.click(thirdRow); await userEvent.click(thirdRow);
expect( expect(
screen.getByRole('row', { screen.getByRole('row', {
@ -82,7 +82,7 @@ describe('Tasks', () => {
}); });
describe('Action button', () => { describe('Action button', () => {
const expectDropdownExists = () => { const expectDropdownExists = async () => {
const firstTaskRow = screen.getByRole('row', { const firstTaskRow = screen.getByRole('row', {
name: '1 kafka-connect0:8083 RUNNING', name: '1 kafka-connect0:8083 RUNNING',
}); });
@ -91,13 +91,13 @@ describe('Tasks', () => {
name: 'Dropdown Toggle', name: 'Dropdown Toggle',
}); });
expect(extBtn).toBeEnabled(); expect(extBtn).toBeEnabled();
userEvent.click(extBtn); await userEvent.click(extBtn);
expect(screen.getByRole('menu')).toBeInTheDocument(); expect(screen.getByRole('menu')).toBeInTheDocument();
}; };
it('renders action button', () => { it('renders action button', async () => {
renderComponent(tasks); renderComponent(tasks);
expectDropdownExists(); await expectDropdownExists();
expect( expect(
screen.getAllByRole('button', { name: 'Dropdown Toggle' }).length screen.getAllByRole('button', { name: 'Dropdown Toggle' }).length
).toEqual(tasks.length); ).toEqual(tasks.length);
@ -108,11 +108,11 @@ describe('Tasks', () => {
it('works as expected', async () => { it('works as expected', async () => {
renderComponent(tasks); renderComponent(tasks);
expectDropdownExists(); await expectDropdownExists();
const actionBtn = screen.getAllByRole('menuitem'); const actionBtn = screen.getAllByRole('menuitem');
expect(actionBtn[0]).toHaveTextContent('Restart task'); expect(actionBtn[0]).toHaveTextContent('Restart task');
userEvent.click(actionBtn[0]); await userEvent.click(actionBtn[0]);
expect( expect(
screen.getByText('Are you sure you want to restart the task?') screen.getByText('Are you sure you want to restart the task?')
).toBeInTheDocument(); ).toBeInTheDocument();

View file

@ -5,7 +5,7 @@ import ClusterContext, {
initialValue, initialValue,
} from 'components/contexts/ClusterContext'; } from 'components/contexts/ClusterContext';
import List from 'components/Connect/List/List'; import List from 'components/Connect/List/List';
import { act, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { render, WithRoute } from 'lib/testHelpers'; import { render, WithRoute } from 'lib/testHelpers';
import { clusterConnectConnectorPath, clusterConnectorsPath } from 'lib/paths'; import { clusterConnectConnectorPath, clusterConnectorsPath } from 'lib/paths';
@ -52,13 +52,11 @@ describe('Connectors List', () => {
it('opens broker when row clicked', async () => { it('opens broker when row clicked', async () => {
renderComponent(); renderComponent();
await act(() => { await userEvent.click(
userEvent.click( screen.getByRole('row', {
screen.getByRole('row', { name: 'hdfs-source-connector first SOURCE FileStreamSource a b c RUNNING 2 of 2',
name: 'hdfs-source-connector first SOURCE FileStreamSource a b c RUNNING 2 of 2', })
}) );
);
});
await waitFor(() => await waitFor(() =>
expect(mockedUsedNavigate).toBeCalledWith( expect(mockedUsedNavigate).toBeCalledWith(
clusterConnectConnectorPath( clusterConnectConnectorPath(
@ -105,7 +103,7 @@ describe('Connectors List', () => {
const submitButton = screen.getAllByRole('button', { const submitButton = screen.getAllByRole('button', {
name: 'Confirm', name: 'Confirm',
})[0]; })[0];
await act(() => userEvent.click(submitButton)); await userEvent.click(submitButton);
expect(mockDelete).toHaveBeenCalledWith(); expect(mockDelete).toHaveBeenCalledWith();
}); });

View file

@ -31,16 +31,14 @@ jest.mock('lib/hooks/api/kafkaConnect', () => ({
describe('New', () => { describe('New', () => {
const clusterName = 'my-cluster'; const clusterName = 'my-cluster';
const simulateFormSubmit = async () => { const simulateFormSubmit = async () => {
await act(() => { await userEvent.type(
userEvent.type( screen.getByPlaceholderText('Connector Name'),
screen.getByPlaceholderText('Connector Name'), 'my-connector'
'my-connector' );
); await userEvent.type(
userEvent.type( screen.getByPlaceholderText('json'),
screen.getByPlaceholderText('json'), '{"class":"MyClass"}'.replace(/[{[]/g, '$&$&')
'{"class":"MyClass"}'.replace(/[{[]/g, '$&$&') );
);
});
expect(screen.getByPlaceholderText('json')).toHaveValue( expect(screen.getByPlaceholderText('json')).toHaveValue(
'{"class":"MyClass"}' '{"class":"MyClass"}'

View file

@ -33,25 +33,24 @@ const resetConsumerGroupOffsetsMockCalled = () =>
).toBeTruthy(); ).toBeTruthy();
const selectresetTypeAndPartitions = async (resetType: string) => { const selectresetTypeAndPartitions = async (resetType: string) => {
userEvent.click(screen.getByLabelText('Reset Type')); await userEvent.click(screen.getByLabelText('Reset Type'));
userEvent.click(screen.getByText(resetType)); await userEvent.click(screen.getByText(resetType));
userEvent.click(screen.getByText('Select...')); await userEvent.click(screen.getByText('Select...'));
await waitFor(() => {
userEvent.click(screen.getByText('Partition #0')); await userEvent.click(screen.getByText('Partition #0'));
});
}; };
const resetConsumerGroupOffsetsWith = async ( const resetConsumerGroupOffsetsWith = async (
resetType: string, resetType: string,
offset: null | number = null offset: null | number = null
) => { ) => {
userEvent.click(screen.getByLabelText('Reset Type')); await userEvent.click(screen.getByLabelText('Reset Type'));
const options = screen.getAllByText(resetType); const options = screen.getAllByText(resetType);
userEvent.click(options.length > 1 ? options[1] : options[0]); await userEvent.click(options.length > 1 ? options[1] : options[0]);
userEvent.click(screen.getByText('Select...')); await userEvent.click(screen.getByText('Select...'));
await waitFor(() => {
userEvent.click(screen.getByText('Partition #0')); await userEvent.click(screen.getByText('Partition #0'));
});
fetchMock.postOnce( fetchMock.postOnce(
`/api/clusters/${clusterName}/consumer-groups/${groupId}/offsets`, `/api/clusters/${clusterName}/consumer-groups/${groupId}/offsets`,
200, 200,
@ -64,7 +63,7 @@ const resetConsumerGroupOffsetsWith = async (
}, },
} }
); );
userEvent.click(screen.getByText('Submit')); await userEvent.click(screen.getByText('Submit'));
await waitFor(() => resetConsumerGroupOffsetsMockCalled()); await waitFor(() => resetConsumerGroupOffsetsMockCalled());
}; };
@ -116,14 +115,14 @@ describe('ResetOffsets', () => {
}, },
} }
); );
await waitFor(() => {
userEvent.click(screen.getAllByLabelText('Partition #0')[1]); await userEvent.click(screen.getAllByLabelText('Partition #0')[1]);
});
await waitFor(() => { await userEvent.keyboard('10');
userEvent.keyboard('10');
}); await userEvent.click(screen.getByText('Submit'));
userEvent.click(screen.getByText('Submit'));
await waitFor(() => resetConsumerGroupOffsetsMockCalled()); await resetConsumerGroupOffsetsMockCalled();
}); });
it('calls resetConsumerGroupOffsets with TIMESTAMP', async () => { it('calls resetConsumerGroupOffsets with TIMESTAMP', async () => {
await selectresetTypeAndPartitions('TIMESTAMP'); await selectresetTypeAndPartitions('TIMESTAMP');
@ -139,7 +138,7 @@ describe('ResetOffsets', () => {
}, },
} }
); );
userEvent.click(screen.getByText('Submit')); await userEvent.click(screen.getByText('Submit'));
await waitFor(() => await waitFor(() =>
expect( expect(
screen.getByText("This field shouldn't be empty!") screen.getByText("This field shouldn't be empty!")

View file

@ -13,7 +13,6 @@ import {
waitForElementToBeRemoved, waitForElementToBeRemoved,
} from '@testing-library/dom'; } from '@testing-library/dom';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { act } from '@testing-library/react';
const clusterName = 'cluster1'; const clusterName = 'cluster1';
const { groupId } = consumerGroupPayload; const { groupId } = consumerGroupPayload;
@ -71,7 +70,7 @@ describe('Details component', () => {
}); });
it('handles [Reset offset] click', async () => { it('handles [Reset offset] click', async () => {
userEvent.click(screen.getByText('Reset offset')); await userEvent.click(screen.getByText('Reset offset'));
expect(mockNavigate).toHaveBeenLastCalledWith( expect(mockNavigate).toHaveBeenLastCalledWith(
clusterConsumerGroupResetRelativePath clusterConsumerGroupResetRelativePath
); );
@ -86,19 +85,19 @@ describe('Details component', () => {
it('shows confirmation modal on consumer group delete', async () => { it('shows confirmation modal on consumer group delete', async () => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
userEvent.click(screen.getByText('Delete consumer group')); await userEvent.click(screen.getByText('Delete consumer group'));
await waitFor(() => await waitFor(() =>
expect(screen.queryByRole('dialog')).toBeInTheDocument() expect(screen.queryByRole('dialog')).toBeInTheDocument()
); );
userEvent.click(screen.getByText('Cancel')); await userEvent.click(screen.getByText('Cancel'));
expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
}); });
it('handles [Delete consumer group] click', async () => { it('handles [Delete consumer group] click', async () => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument(); expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
await act(() => {
userEvent.click(screen.getByText('Delete consumer group')); await userEvent.click(screen.getByText('Delete consumer group'));
});
expect(screen.queryByRole('dialog')).toBeInTheDocument(); expect(screen.queryByRole('dialog')).toBeInTheDocument();
const deleteConsumerGroupMock = fetchMock.deleteOnce( const deleteConsumerGroupMock = fetchMock.deleteOnce(
`/api/clusters/${clusterName}/consumer-groups/${groupId}`, `/api/clusters/${clusterName}/consumer-groups/${groupId}`,

View file

@ -39,8 +39,8 @@ describe('ListItem', () => {
expect(screen.getByRole('row')).toBeInTheDocument(); expect(screen.getByRole('row')).toBeInTheDocument();
}); });
it('should renders list item with topic content open', () => { it('should renders list item with topic content open', async () => {
userEvent.click(screen.getAllByRole('cell')[0].children[0]); await userEvent.click(screen.getAllByRole('cell')[0].children[0]);
expect(screen.getByText('Consumer ID')).toBeInTheDocument(); expect(screen.getByText('Consumer ID')).toBeInTheDocument();
}); });
}); });

View file

@ -48,10 +48,10 @@ describe('List', () => {
expect(screen.getByText('groupId2')).toBeInTheDocument(); expect(screen.getByText('groupId2')).toBeInTheDocument();
}); });
it('handles onRowClick', () => { it('handles onRowClick', async () => {
const row = screen.getByRole('row', { name: 'groupId1 0 1 1' }); const row = screen.getByRole('row', { name: 'groupId1 0 1 1' });
expect(row).toBeInTheDocument(); expect(row).toBeInTheDocument();
userEvent.click(row); await userEvent.click(row);
expect(mockedUsedNavigate).toHaveBeenCalledWith( expect(mockedUsedNavigate).toHaveBeenCalledWith(
clusterConsumerGroupDetailsPath(':clusterName', 'groupId1') clusterConsumerGroupDetailsPath(':clusterName', 'groupId1')
); );

View file

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { act, screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import ClustersWidget from 'components/Dashboard/ClustersWidget/ClustersWidget'; import ClustersWidget from 'components/Dashboard/ClustersWidget/ClustersWidget';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { render } from 'lib/testHelpers'; import { render } from 'lib/testHelpers';
@ -16,18 +16,16 @@ describe('ClustersWidget', () => {
data: clustersPayload, data: clustersPayload,
isSuccess: true, isSuccess: true,
})); }));
await act(() => { await render(<ClustersWidget />);
render(<ClustersWidget />);
});
}); });
it('renders clusterWidget list', () => { it('renders clusterWidget list', () => {
expect(screen.getAllByRole('row').length).toBe(3); expect(screen.getAllByRole('row').length).toBe(3);
}); });
it('hides online cluster widgets', () => { it('hides online cluster widgets', async () => {
expect(screen.getAllByRole('row').length).toBe(3); expect(screen.getAllByRole('row').length).toBe(3);
userEvent.click(screen.getByRole('checkbox')); await userEvent.click(screen.getByRole('checkbox'));
expect(screen.getAllByRole('row').length).toBe(2); expect(screen.getAllByRole('row').length).toBe(2);
}); });

View file

@ -7,7 +7,6 @@ import KsqlDbItem, {
} from 'components/KsqlDb/List/KsqlDbItem/KsqlDbItem'; } from 'components/KsqlDb/List/KsqlDbItem/KsqlDbItem';
import { screen } from '@testing-library/dom'; import { screen } from '@testing-library/dom';
import { fetchKsqlDbTablesPayload } from 'redux/reducers/ksqlDb/__test__/fixtures'; import { fetchKsqlDbTablesPayload } from 'redux/reducers/ksqlDb/__test__/fixtures';
import { act } from '@testing-library/react';
describe('KsqlDbItem', () => { describe('KsqlDbItem', () => {
const tablesPathname = clusterKsqlDbTablesPath(); const tablesPathname = clusterKsqlDbTablesPath();
@ -27,37 +26,34 @@ describe('KsqlDbItem', () => {
); );
}; };
it('renders progressbar when fetching tables and streams', async () => { it('renders progressbar when fetching tables and streams', () => {
await act(() => renderComponent({ fetching: true })); renderComponent({ fetching: true });
expect(screen.getByRole('progressbar')).toBeInTheDocument(); expect(screen.getByRole('progressbar')).toBeInTheDocument();
}); });
it('show no text if no data found', async () => { it('show no text if no data found', () => {
await act(() => renderComponent({})); renderComponent({});
expect(screen.getByText('No tables or streams found')).toBeInTheDocument(); expect(screen.getByText('No tables or streams found')).toBeInTheDocument();
}); });
it('renders with tables', async () => { it('renders with tables', () => {
await act(() => renderComponent({
renderComponent({ rows: {
rows: { tables: fetchKsqlDbTablesPayload.tables,
tables: fetchKsqlDbTablesPayload.tables, streams: [],
streams: [], },
}, });
})
);
expect(screen.getByRole('table').querySelectorAll('td')).toHaveLength(10); expect(screen.getByRole('table').querySelectorAll('td')).toHaveLength(10);
}); });
it('renders with streams', async () => { it('renders with streams', () => {
await act(() => renderComponent({
renderComponent({ type: KsqlDbItemType.Streams,
type: KsqlDbItemType.Streams, rows: {
rows: { tables: [],
tables: [], streams: fetchKsqlDbTablesPayload.streams,
streams: fetchKsqlDbTablesPayload.streams, },
}, });
})
);
expect(screen.getByRole('table').querySelectorAll('td')).toHaveLength(10); expect(screen.getByRole('table').querySelectorAll('td')).toHaveLength(10);
}); });
}); });

View file

@ -3,7 +3,6 @@ import React from 'react';
import QueryForm, { Props } from 'components/KsqlDb/Query/QueryForm/QueryForm'; import QueryForm, { Props } from 'components/KsqlDb/Query/QueryForm/QueryForm';
import { screen, waitFor, within } from '@testing-library/dom'; import { screen, waitFor, within } from '@testing-library/dom';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { act } from '@testing-library/react';
const renderComponent = (props: Props) => render(<QueryForm {...props} />); const renderComponent = (props: Props) => render(<QueryForm {...props} />);
@ -57,10 +56,9 @@ describe('QueryForm', () => {
submitHandler: submitFn, submitHandler: submitFn,
}); });
await act(() => await userEvent.click(screen.getByRole('button', { name: 'Execute' }));
userEvent.click(screen.getByRole('button', { name: 'Execute' }))
); await waitFor(() => {
waitFor(() => {
expect(screen.getByText('ksql is a required field')).toBeInTheDocument(); expect(screen.getByText('ksql is a required field')).toBeInTheDocument();
expect(submitFn).not.toBeCalled(); expect(submitFn).not.toBeCalled();
}); });
@ -76,12 +74,16 @@ describe('QueryForm', () => {
submitHandler: submitFn, submitHandler: submitFn,
}); });
await act(() => { const textbox = screen.getAllByRole('textbox');
userEvent.paste(screen.getAllByRole('textbox')[0], 'show tables;'); textbox[0].focus();
userEvent.paste(screen.getByRole('textbox', { name: 'key' }), 'test'); await userEvent.paste('show tables;');
userEvent.paste(screen.getByRole('textbox', { name: 'value' }), 'test'); const key = screen.getByRole('textbox', { name: 'key' });
userEvent.click(screen.getByRole('button', { name: 'Execute' })); key.focus();
}); await userEvent.paste('test');
const value = screen.getByRole('textbox', { name: 'value' });
value.focus();
await userEvent.paste('test');
await userEvent.click(screen.getByRole('button', { name: 'Execute' }));
expect( expect(
screen.queryByText('ksql is a required field') screen.queryByText('ksql is a required field')
@ -106,8 +108,8 @@ describe('QueryForm', () => {
expect(screen.getByRole('button', { name: 'Clear results' })).toBeEnabled(); expect(screen.getByRole('button', { name: 'Clear results' })).toBeEnabled();
await act(() => await userEvent.click(
userEvent.click(screen.getByRole('button', { name: 'Clear results' })) screen.getByRole('button', { name: 'Clear results' })
); );
expect(clearFn).toBeCalled(); expect(clearFn).toBeCalled();
@ -125,39 +127,12 @@ describe('QueryForm', () => {
expect(screen.getByRole('button', { name: 'Stop query' })).toBeEnabled(); expect(screen.getByRole('button', { name: 'Stop query' })).toBeEnabled();
await act(() => await userEvent.click(screen.getByRole('button', { name: 'Stop query' }));
userEvent.click(screen.getByRole('button', { name: 'Stop query' }))
);
expect(cancelFn).toBeCalled(); expect(cancelFn).toBeCalled();
}); });
it('submits form with ctrl+enter on KSQL editor', async () => { it('add new property', async () => {
const submitFn = jest.fn();
renderComponent({
fetching: false,
hasResults: false,
handleClearResults: jest.fn(),
handleSSECancel: jest.fn(),
submitHandler: submitFn,
});
await act(() => {
userEvent.paste(
within(screen.getByLabelText('KSQL')).getByRole('textbox'),
'show tables;'
);
userEvent.type(
within(screen.getByLabelText('KSQL')).getByRole('textbox'),
'{ctrl}{enter}'
);
});
expect(submitFn.mock.calls.length).toBe(1);
});
it('adds new property', async () => {
renderComponent({ renderComponent({
fetching: false, fetching: false,
hasResults: false, hasResults: false,
@ -168,11 +143,9 @@ describe('QueryForm', () => {
const textbox = screen.getByLabelText('key'); const textbox = screen.getByLabelText('key');
await userEvent.type(textbox, 'prop_name'); await userEvent.type(textbox, 'prop_name');
await act(() => { await userEvent.click(
userEvent.click( screen.getByRole('button', { name: 'Add Stream Property' })
screen.getByRole('button', { name: 'Add Stream Property' }) );
);
});
expect(screen.getAllByRole('textbox', { name: 'key' }).length).toEqual(2); expect(screen.getAllByRole('textbox', { name: 'key' }).length).toEqual(2);
}); });
@ -185,11 +158,9 @@ describe('QueryForm', () => {
submitHandler: jest.fn(), submitHandler: jest.fn(),
}); });
await act(() => { await userEvent.click(
userEvent.click( screen.getByRole('button', { name: 'Add Stream Property' })
screen.getByRole('button', { name: 'Add Stream Property' }) );
);
});
expect(screen.getAllByRole('textbox', { name: 'key' }).length).toEqual(1); expect(screen.getAllByRole('textbox', { name: 'key' }).length).toEqual(1);
}); });
@ -201,16 +172,18 @@ describe('QueryForm', () => {
handleSSECancel: jest.fn(), handleSSECancel: jest.fn(),
submitHandler: jest.fn(), submitHandler: jest.fn(),
}); });
const textBoxes = screen.getAllByRole('textbox', { name: 'key' });
textBoxes[0].focus();
await userEvent.paste('test');
await userEvent.click(
screen.getByRole('button', { name: 'Add Stream Property' })
);
await userEvent.click(screen.getAllByLabelText('deleteProperty')[0]);
await act(() => { await screen.getByRole('button', { name: 'Add Stream Property' });
userEvent.paste(screen.getByRole('textbox', { name: 'key' }), 'test');
userEvent.click( await userEvent.click(screen.getAllByLabelText('deleteProperty')[0]);
screen.getByRole('button', { name: 'Add Stream Property' })
); expect(textBoxes.length).toEqual(1);
});
await act(() => {
userEvent.click(screen.getAllByLabelText('deleteProperty')[0]);
});
expect(screen.getAllByRole('textbox', { name: 'key' }).length).toEqual(1);
}); });
}); });

View file

@ -6,7 +6,6 @@ import Query, {
import { screen } from '@testing-library/dom'; import { screen } from '@testing-library/dom';
import fetchMock from 'fetch-mock'; import fetchMock from 'fetch-mock';
import { clusterKsqlDbQueryPath } from 'lib/paths'; import { clusterKsqlDbQueryPath } from 'lib/paths';
import { act } from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
const clusterName = 'testLocal'; const clusterName = 'testLocal';
@ -41,10 +40,10 @@ describe('Query', () => {
}); });
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole('textbox');
const textAreaElement = inputs[0] as HTMLTextAreaElement; const textAreaElement = inputs[0] as HTMLTextAreaElement;
await act(() => {
userEvent.paste(textAreaElement, 'show tables;'); textAreaElement.focus();
userEvent.click(screen.getByRole('button', { name: 'Execute' })); await userEvent.paste('show tables;');
}); await userEvent.click(screen.getByRole('button', { name: 'Execute' }));
expect(mock.calls().length).toBe(1); expect(mock.calls().length).toBe(1);
}); });
@ -59,18 +58,20 @@ describe('Query', () => {
Object.defineProperty(window, 'EventSource', { Object.defineProperty(window, 'EventSource', {
value: EventSourceMock, value: EventSourceMock,
}); });
await act(() => {
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole('textbox');
const textAreaElement = inputs[0] as HTMLTextAreaElement; const textAreaElement = inputs[0] as HTMLTextAreaElement;
userEvent.paste(textAreaElement, 'show tables;'); textAreaElement.focus();
}); await userEvent.paste('show tables;');
await act(() => {
userEvent.paste(screen.getByLabelText('key'), 'key'); const key = screen.getByLabelText('key');
userEvent.paste(screen.getByLabelText('value'), 'value'); key.focus();
}); await userEvent.paste('key');
await act(() => { const value = screen.getByLabelText('value');
userEvent.click(screen.getByRole('button', { name: 'Execute' })); value.focus();
}); await userEvent.paste('value');
await userEvent.click(screen.getByRole('button', { name: 'Execute' }));
expect(mock.calls().length).toBe(1); expect(mock.calls().length).toBe(1);
}); });

View file

@ -19,19 +19,19 @@ describe('ClusterMenu', () => {
const getKafkaConnect = () => screen.getByTitle('Kafka Connect'); const getKafkaConnect = () => screen.getByTitle('Kafka Connect');
const getCluster = () => screen.getByText(onlineClusterPayload.name); const getCluster = () => screen.getByText(onlineClusterPayload.name);
it('renders cluster menu with default set of features', () => { it('renders cluster menu with default set of features', async () => {
render(setupComponent(onlineClusterPayload)); render(setupComponent(onlineClusterPayload));
expect(getCluster()).toBeInTheDocument(); expect(getCluster()).toBeInTheDocument();
expect(getMenuItems().length).toEqual(1); expect(getMenuItems().length).toEqual(1);
userEvent.click(getMenuItem()); await userEvent.click(getMenuItem());
expect(getMenuItems().length).toEqual(4); expect(getMenuItems().length).toEqual(4);
expect(getBrokers()).toBeInTheDocument(); expect(getBrokers()).toBeInTheDocument();
expect(getTopics()).toBeInTheDocument(); expect(getTopics()).toBeInTheDocument();
expect(getConsumers()).toBeInTheDocument(); expect(getConsumers()).toBeInTheDocument();
}); });
it('renders cluster menu with correct set of features', () => { it('renders cluster menu with correct set of features', async () => {
render( render(
setupComponent({ setupComponent({
...onlineClusterPayload, ...onlineClusterPayload,
@ -43,7 +43,7 @@ describe('ClusterMenu', () => {
}) })
); );
expect(getMenuItems().length).toEqual(1); expect(getMenuItems().length).toEqual(1);
userEvent.click(getMenuItem()); await userEvent.click(getMenuItem());
expect(getMenuItems().length).toEqual(7); expect(getMenuItems().length).toEqual(7);
expect(getBrokers()).toBeInTheDocument(); expect(getBrokers()).toBeInTheDocument();
@ -64,7 +64,7 @@ describe('ClusterMenu', () => {
expect(getTopics()).toBeInTheDocument(); expect(getTopics()).toBeInTheDocument();
expect(getConsumers()).toBeInTheDocument(); expect(getConsumers()).toBeInTheDocument();
}); });
it('makes Kafka Connect link active', () => { it('makes Kafka Connect link active', async () => {
render( render(
setupComponent({ setupComponent({
...onlineClusterPayload, ...onlineClusterPayload,
@ -73,7 +73,7 @@ describe('ClusterMenu', () => {
{ initialEntries: [clusterConnectorsPath(onlineClusterPayload.name)] } { initialEntries: [clusterConnectorsPath(onlineClusterPayload.name)] }
); );
expect(getMenuItems().length).toEqual(1); expect(getMenuItems().length).toEqual(1);
userEvent.click(getMenuItem()); await userEvent.click(getMenuItem());
expect(getMenuItems().length).toEqual(5); expect(getMenuItems().length).toEqual(5);
const kafkaConnect = getKafkaConnect(); const kafkaConnect = getKafkaConnect();

View file

@ -2,7 +2,6 @@ import React from 'react';
import Nav from 'components/Nav/Nav'; import Nav from 'components/Nav/Nav';
import { screen } from '@testing-library/react'; import { screen } from '@testing-library/react';
import { render } from 'lib/testHelpers'; import { render } from 'lib/testHelpers';
import { act } from 'react-dom/test-utils';
import { Cluster } from 'generated-sources'; import { Cluster } from 'generated-sources';
import { useClusters } from 'lib/hooks/api/clusters'; import { useClusters } from 'lib/hooks/api/clusters';
import { import {
@ -15,28 +14,26 @@ jest.mock('lib/hooks/api/clusters', () => ({
})); }));
describe('Nav', () => { describe('Nav', () => {
const renderComponent = async (payload: Cluster[] = []) => { const renderComponent = (payload: Cluster[] = []) => {
(useClusters as jest.Mock).mockImplementation(() => ({ (useClusters as jest.Mock).mockImplementation(() => ({
data: payload, data: payload,
isSuccess: true, isSuccess: true,
})); }));
await act(() => { render(<Nav />);
render(<Nav />);
});
}; };
const getDashboard = () => screen.getByText('Dashboard'); const getDashboard = () => screen.getByText('Dashboard');
const getMenuItemsCount = () => screen.getAllByRole('menuitem').length; const getMenuItemsCount = () => screen.getAllByRole('menuitem').length;
it('renders loader', async () => { it('renders loader', () => {
await renderComponent(); renderComponent();
expect(getMenuItemsCount()).toEqual(1); expect(getMenuItemsCount()).toEqual(1);
expect(getDashboard()).toBeInTheDocument(); expect(getDashboard()).toBeInTheDocument();
}); });
it('renders ClusterMenu', async () => { it('renders ClusterMenu', () => {
await renderComponent([onlineClusterPayload, offlineClusterPayload]); renderComponent([onlineClusterPayload, offlineClusterPayload]);
expect(screen.getAllByRole('menu').length).toEqual(3); expect(screen.getAllByRole('menu').length).toEqual(3);
expect(getMenuItemsCount()).toEqual(3); expect(getMenuItemsCount()).toEqual(3);
expect(getDashboard()).toBeInTheDocument(); expect(getDashboard()).toBeInTheDocument();

View file

@ -56,9 +56,7 @@ describe('Details', () => {
schemasAPIVersionsUrl, schemasAPIVersionsUrl,
404 404
); );
await act(() => { await renderComponent();
renderComponent();
});
await waitFor(() => { await waitFor(() => {
expect(schemasAPILatestMock.called()).toBeTruthy(); expect(schemasAPILatestMock.called()).toBeTruthy();

View file

@ -19,7 +19,7 @@ const renderComponent = () => {
}; };
describe('SchemaVersion', () => { describe('SchemaVersion', () => {
it('renders versions', () => { it('renders versions', async () => {
renderComponent(); renderComponent();
}); });
}); });

View file

@ -45,9 +45,7 @@ describe('Edit', () => {
describe('fetch failed', () => { describe('fetch failed', () => {
it('renders page loader', async () => { it('renders page loader', async () => {
const schemasAPILatestMock = fetchMock.getOnce(schemasAPILatestUrl, 404); const schemasAPILatestMock = fetchMock.getOnce(schemasAPILatestUrl, 404);
await act(() => { await renderComponent();
renderComponent();
});
await waitFor(() => expect(schemasAPILatestMock.called()).toBeTruthy()); await waitFor(() => expect(schemasAPILatestMock.called()).toBeTruthy());
expect(screen.getByRole('progressbar')).toBeInTheDocument(); expect(screen.getByRole('progressbar')).toBeInTheDocument();
expect(screen.queryByText(schemaVersion.subject)).not.toBeInTheDocument(); expect(screen.queryByText(schemaVersion.subject)).not.toBeInTheDocument();

View file

@ -9,11 +9,11 @@ import fetchMock from 'fetch-mock';
const clusterName = 'testClusterName'; const clusterName = 'testClusterName';
const selectForwardOption = () => { const selectForwardOption = async () => {
const dropdownElement = screen.getByRole('listbox'); const dropdownElement = screen.getByRole('listbox');
// clicks to open dropdown // clicks to open dropdown
userEvent.click(within(dropdownElement).getByRole('option')); await userEvent.click(within(dropdownElement).getByRole('option'));
userEvent.click( await userEvent.click(
screen.getByText(CompatibilityLevelCompatibilityEnum.FORWARD) screen.getByText(CompatibilityLevelCompatibilityEnum.FORWARD)
); );
}; };
@ -59,19 +59,19 @@ describe('GlobalSchemaSelector', () => {
it('shows popup when select value is changed', async () => { it('shows popup when select value is changed', async () => {
expectOptionIsSelected(CompatibilityLevelCompatibilityEnum.FULL); expectOptionIsSelected(CompatibilityLevelCompatibilityEnum.FULL);
selectForwardOption(); await selectForwardOption();
expect(screen.getByText('Confirm the action')).toBeInTheDocument(); expect(screen.getByText('Confirm the action')).toBeInTheDocument();
}); });
it('resets select value when cancel is clicked', () => { it('resets select value when cancel is clicked', async () => {
selectForwardOption(); await selectForwardOption();
userEvent.click(screen.getByText('Cancel')); await userEvent.click(screen.getByText('Cancel'));
expect(screen.queryByText('Confirm the action')).not.toBeInTheDocument(); expect(screen.queryByText('Confirm the action')).not.toBeInTheDocument();
expectOptionIsSelected(CompatibilityLevelCompatibilityEnum.FULL); expectOptionIsSelected(CompatibilityLevelCompatibilityEnum.FULL);
}); });
it('sets new schema when confirm is clicked', async () => { it('sets new schema when confirm is clicked', async () => {
selectForwardOption(); await selectForwardOption();
const putNewCompatibilityMock = fetchMock.putOnce( const putNewCompatibilityMock = fetchMock.putOnce(
`api/clusters/${clusterName}/schemas/compatibility`, `api/clusters/${clusterName}/schemas/compatibility`,
200, 200,

View file

@ -109,14 +109,14 @@ describe('List', () => {
expect(screen.getByText(schemaVersion1.subject)).toBeInTheDocument(); expect(screen.getByText(schemaVersion1.subject)).toBeInTheDocument();
expect(screen.getByText(schemaVersion2.subject)).toBeInTheDocument(); expect(screen.getByText(schemaVersion2.subject)).toBeInTheDocument();
}); });
it('handles onRowClick', () => { it('handles onRowClick', async () => {
const { id, schemaType, subject, version, compatibilityLevel } = const { id, schemaType, subject, version, compatibilityLevel } =
schemaVersion2; schemaVersion2;
const row = screen.getByRole('row', { const row = screen.getByRole('row', {
name: `${subject} ${id} ${schemaType} ${version} ${compatibilityLevel}`, name: `${subject} ${id} ${schemaType} ${version} ${compatibilityLevel}`,
}); });
expect(row).toBeInTheDocument(); expect(row).toBeInTheDocument();
userEvent.click(row); await userEvent.click(row);
expect(mockedUsedNavigate).toHaveBeenCalledWith( expect(mockedUsedNavigate).toHaveBeenCalledWith(
clusterSchemaPath(clusterName, subject) clusterSchemaPath(clusterName, subject)
); );

View file

@ -10,8 +10,8 @@ const subjectValue = 'subject';
const schemaValue = 'schema'; const schemaValue = 'schema';
describe('New Component', () => { describe('New Component', () => {
beforeEach(() => { beforeEach(async () => {
render( await render(
<WithRoute path={clusterSchemaNewPath()}> <WithRoute path={clusterSchemaNewPath()}>
<New /> <New />
</WithRoute>, </WithRoute>,
@ -33,14 +33,14 @@ describe('New Component', () => {
const schema = screen.getAllByRole('textbox')[1]; const schema = screen.getAllByRole('textbox')[1];
const schemaTypeSelect = screen.getByRole('listbox'); const schemaTypeSelect = screen.getByRole('listbox');
await act(() => { await act(async () => {
userEvent.type(subject, subjectValue); await userEvent.type(subject, subjectValue);
}); });
await act(() => { await act(async () => {
userEvent.type(schema, schemaValue); await userEvent.type(schema, schemaValue);
}); });
await act(() => { await act(async () => {
userEvent.selectOptions(schemaTypeSelect, ['AVRO']); await userEvent.selectOptions(schemaTypeSelect, ['AVRO']);
}); });
const submitBtn = screen.getByRole('button', { name: /Submit/i }); const submitBtn = screen.getByRole('button', { name: /Submit/i });

View file

@ -33,14 +33,14 @@ describe('ListPage Component', () => {
renderComponent(); renderComponent();
}); });
it('handles switch of Internal Topics visibility', () => { it('handles switch of Internal Topics visibility', async () => {
const switchInput = screen.getByLabelText('Show Internal Topics'); const switchInput = screen.getByLabelText('Show Internal Topics');
expect(switchInput).toBeInTheDocument(); expect(switchInput).toBeInTheDocument();
expect(global.localStorage.getItem('hideInternalTopics')).toBeNull(); expect(global.localStorage.getItem('hideInternalTopics')).toBeNull();
userEvent.click(switchInput); await userEvent.click(switchInput);
expect(global.localStorage.getItem('hideInternalTopics')).toBeTruthy(); expect(global.localStorage.getItem('hideInternalTopics')).toBeTruthy();
userEvent.click(switchInput); await userEvent.click(switchInput);
expect(global.localStorage.getItem('hideInternalTopics')).toBeNull(); expect(global.localStorage.getItem('hideInternalTopics')).toBeNull();
}); });

View file

@ -131,8 +131,8 @@ describe('TopicTable Components', () => {
expect(screen.getAllByRole('checkbox')[2]).toBeEnabled(); expect(screen.getAllByRole('checkbox')[2]).toBeEnabled();
}); });
describe('when only one topic is selected', () => { describe('when only one topic is selected', () => {
beforeEach(() => { beforeEach(async () => {
userEvent.click(screen.getAllByRole('checkbox')[1]); await userEvent.click(screen.getAllByRole('checkbox')[1]);
}); });
it('renders batch actions bar', () => { it('renders batch actions bar', () => {
expect(getButtonByName('Delete selected topics')).toBeEnabled(); expect(getButtonByName('Delete selected topics')).toBeEnabled();
@ -143,9 +143,9 @@ describe('TopicTable Components', () => {
}); });
}); });
describe('when more then one topics are selected', () => { describe('when more then one topics are selected', () => {
beforeEach(() => { beforeEach(async () => {
userEvent.click(screen.getAllByRole('checkbox')[1]); await userEvent.click(screen.getAllByRole('checkbox')[1]);
userEvent.click(screen.getAllByRole('checkbox')[2]); await userEvent.click(screen.getAllByRole('checkbox')[2]);
}); });
it('renders batch actions bar', () => { it('renders batch actions bar', () => {
expect(getButtonByName('Delete selected topics')).toBeEnabled(); expect(getButtonByName('Delete selected topics')).toBeEnabled();
@ -190,12 +190,12 @@ describe('TopicTable Components', () => {
}); });
}); });
describe('Action buttons', () => { describe('Action buttons', () => {
const expectDropdownExists = () => { const expectDropdownExists = async () => {
const btn = screen.getByRole('button', { const btn = screen.getByRole('button', {
name: 'Dropdown Toggle', name: 'Dropdown Toggle',
}); });
expect(btn).toBeEnabled(); expect(btn).toBeEnabled();
userEvent.click(btn); await userEvent.click(btn);
expect(screen.getByRole('menu')).toBeInTheDocument(); expect(screen.getByRole('menu')).toBeInTheDocument();
}; };
it('renders disable action buttons for read-only cluster', () => { it('renders disable action buttons for read-only cluster', () => {
@ -204,7 +204,7 @@ describe('TopicTable Components', () => {
expect(btns[0]).toBeDisabled(); expect(btns[0]).toBeDisabled();
expect(btns[1]).toBeDisabled(); expect(btns[1]).toBeDisabled();
}); });
it('renders action buttons', () => { it('renders action buttons', async () => {
renderComponent({ topics: topicsPayload, pageCount: 1 }); renderComponent({ topics: topicsPayload, pageCount: 1 });
expect( expect(
screen.getAllByRole('button', { name: 'Dropdown Toggle' }).length screen.getAllByRole('button', { name: 'Dropdown Toggle' }).length
@ -228,7 +228,7 @@ describe('TopicTable Components', () => {
name: 'Dropdown Toggle', name: 'Dropdown Toggle',
}); });
expect(extBtn).toBeEnabled(); expect(extBtn).toBeEnabled();
userEvent.click(extBtn); await userEvent.click(extBtn);
expect(screen.getByRole('menu')).toBeInTheDocument(); expect(screen.getByRole('menu')).toBeInTheDocument();
}); });
describe('and clear messages action', () => { describe('and clear messages action', () => {
@ -241,7 +241,7 @@ describe('TopicTable Components', () => {
}, },
], ],
}); });
expectDropdownExists(); await expectDropdownExists();
const actionBtn = screen.getAllByRole('menuitem'); const actionBtn = screen.getAllByRole('menuitem');
expect(actionBtn[0]).toHaveTextContent('Clear Messages'); expect(actionBtn[0]).toHaveTextContent('Clear Messages');
expect(actionBtn[0]).not.toHaveAttribute('aria-disabled'); expect(actionBtn[0]).not.toHaveAttribute('aria-disabled');
@ -255,7 +255,7 @@ describe('TopicTable Components', () => {
}, },
], ],
}); });
expectDropdownExists(); await expectDropdownExists();
const actionBtn = screen.getAllByRole('menuitem'); const actionBtn = screen.getAllByRole('menuitem');
expect(actionBtn[0]).toHaveTextContent('Clear Messages'); expect(actionBtn[0]).toHaveTextContent('Clear Messages');
expect(actionBtn[0]).toHaveAttribute('aria-disabled'); expect(actionBtn[0]).toHaveAttribute('aria-disabled');
@ -269,8 +269,8 @@ describe('TopicTable Components', () => {
}, },
], ],
}); });
expectDropdownExists(); await expectDropdownExists();
userEvent.click(screen.getByText('Clear Messages')); await userEvent.click(screen.getByText('Clear Messages'));
expect( expect(
screen.getByText('Are you sure want to clear topic messages?') screen.getByText('Are you sure want to clear topic messages?')
).toBeInTheDocument(); ).toBeInTheDocument();
@ -284,22 +284,22 @@ describe('TopicTable Components', () => {
describe('and remove topic action', () => { describe('and remove topic action', () => {
it('is visible only when topic deletion allowed for cluster', async () => { it('is visible only when topic deletion allowed for cluster', async () => {
renderComponent({ topics: [topicsPayload[1]] }); renderComponent({ topics: [topicsPayload[1]] });
expectDropdownExists(); await expectDropdownExists();
const actionBtn = screen.getAllByRole('menuitem'); const actionBtn = screen.getAllByRole('menuitem');
expect(actionBtn[2]).toHaveTextContent('Remove Topic'); expect(actionBtn[2]).toHaveTextContent('Remove Topic');
expect(actionBtn[2]).not.toHaveAttribute('aria-disabled'); expect(actionBtn[2]).not.toHaveAttribute('aria-disabled');
}); });
it('is disabled when topic deletion is not allowed for cluster', async () => { it('is disabled when topic deletion is not allowed for cluster', async () => {
renderComponent({ topics: [topicsPayload[1]] }, false, false); renderComponent({ topics: [topicsPayload[1]] }, false, false);
expectDropdownExists(); await expectDropdownExists();
const actionBtn = screen.getAllByRole('menuitem'); const actionBtn = screen.getAllByRole('menuitem');
expect(actionBtn[2]).toHaveTextContent('Remove Topic'); expect(actionBtn[2]).toHaveTextContent('Remove Topic');
expect(actionBtn[2]).toHaveAttribute('aria-disabled'); expect(actionBtn[2]).toHaveAttribute('aria-disabled');
}); });
it('works as expected', async () => { it('works as expected', async () => {
renderComponent({ topics: [topicsPayload[1]] }); renderComponent({ topics: [topicsPayload[1]] });
expectDropdownExists(); await expectDropdownExists();
userEvent.click(screen.getByText('Remove Topic')); await userEvent.click(screen.getByText('Remove Topic'));
expect(screen.getByText('Confirm the action')).toBeInTheDocument(); expect(screen.getByText('Confirm the action')).toBeInTheDocument();
await waitFor(() => await waitFor(() =>
userEvent.click(screen.getByRole('button', { name: 'Confirm' })) userEvent.click(screen.getByRole('button', { name: 'Confirm' }))
@ -310,8 +310,8 @@ describe('TopicTable Components', () => {
describe('and recreate topic action', () => { describe('and recreate topic action', () => {
it('works as expected', async () => { it('works as expected', async () => {
renderComponent({ topics: [topicsPayload[1]] }); renderComponent({ topics: [topicsPayload[1]] });
expectDropdownExists(); await expectDropdownExists();
userEvent.click(screen.getByText('Recreate Topic')); await userEvent.click(screen.getByText('Recreate Topic'));
expect(screen.getByText('Confirm the action')).toBeInTheDocument(); expect(screen.getByText('Confirm the action')).toBeInTheDocument();
await waitFor(() => await waitFor(() =>
userEvent.click(screen.getByRole('button', { name: 'Confirm' })) userEvent.click(screen.getByRole('button', { name: 'Confirm' }))

View file

@ -60,11 +60,14 @@ describe('New', () => {
it('validates form', async () => { it('validates form', async () => {
await act(() => renderComponent(clusterTopicNewPath(clusterName))); await act(() => renderComponent(clusterTopicNewPath(clusterName)));
await waitFor(() => { await waitFor(async () => {
userEvent.type(screen.getByPlaceholderText('Topic Name'), topicName); await userEvent.type(
screen.getByPlaceholderText('Topic Name'),
topicName
);
}); });
await waitFor(() => { await waitFor(async () => {
userEvent.clear(screen.getByPlaceholderText('Topic Name')); await userEvent.clear(screen.getByPlaceholderText('Topic Name'));
}); });
await waitFor(() => { await waitFor(() => {
expect(screen.getByText('name is a required field')).toBeInTheDocument(); expect(screen.getByText('name is a required field')).toBeInTheDocument();
@ -87,11 +90,14 @@ describe('New', () => {
it('submits valid form', async () => { it('submits valid form', async () => {
await act(() => renderComponent(clusterTopicNewPath(clusterName))); await act(() => renderComponent(clusterTopicNewPath(clusterName)));
await act(() => { await act(async () => {
userEvent.type(screen.getByPlaceholderText('Topic Name'), topicName); await userEvent.type(
screen.getByPlaceholderText('Topic Name'),
topicName
);
}); });
await act(() => { await act(async () => {
userEvent.click(screen.getByText('Create topic')); await userEvent.click(screen.getByText('Create topic'));
}); });
await waitFor(() => expect(createTopicMock).toHaveBeenCalledTimes(1)); await waitFor(() => expect(createTopicMock).toHaveBeenCalledTimes(1));
await waitFor(() => await waitFor(() =>

View file

@ -34,8 +34,8 @@ const renderComponent = (props?: Partial<DangerZoneProps>) =>
{ initialEntries: [clusterTopicPath(clusterName, topicName)] } { initialEntries: [clusterTopicPath(clusterName, topicName)] }
); );
const clickOnDialogSubmitButton = () => { const clickOnDialogSubmitButton = async () => {
userEvent.click( await userEvent.click(
within(screen.getByRole('dialog')).getByRole('button', { within(screen.getByRole('dialog')).getByRole('button', {
name: 'Confirm', name: 'Confirm',
}) })
@ -45,7 +45,7 @@ const clickOnDialogSubmitButton = () => {
const checkDialogThenPressCancel = async () => { const checkDialogThenPressCancel = async () => {
const dialog = screen.getByRole('dialog'); const dialog = screen.getByRole('dialog');
expect(screen.getByRole('dialog')).toBeInTheDocument(); expect(screen.getByRole('dialog')).toBeInTheDocument();
userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' })); await userEvent.click(within(dialog).getByRole('button', { name: 'Cancel' }));
await waitFor(() => await waitFor(() =>
expect(screen.queryByRole('dialog')).not.toBeInTheDocument() expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
); );
@ -91,11 +91,13 @@ describe('DangerZone', () => {
const numberOfPartitionsEditForm = screen.getByRole('form', { const numberOfPartitionsEditForm = screen.getByRole('form', {
name: 'Edit number of partitions', name: 'Edit number of partitions',
}); });
userEvent.type( await userEvent.type(
within(numberOfPartitionsEditForm).getByRole('spinbutton'), within(numberOfPartitionsEditForm).getByRole('spinbutton'),
'4' '4'
); );
userEvent.click(within(numberOfPartitionsEditForm).getByRole('button')); await userEvent.click(
within(numberOfPartitionsEditForm).getByRole('button')
);
await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument()); await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
await waitFor(() => clickOnDialogSubmitButton()); await waitFor(() => clickOnDialogSubmitButton());
expect(mockIncreaseTopicPartitionsCount).toHaveBeenCalledTimes(1); expect(mockIncreaseTopicPartitionsCount).toHaveBeenCalledTimes(1);
@ -119,11 +121,13 @@ describe('DangerZone', () => {
within(replicationFactorEditForm).getByRole('button', { name: 'Submit' }) within(replicationFactorEditForm).getByRole('button', { name: 'Submit' })
).toBeInTheDocument(); ).toBeInTheDocument();
userEvent.type( await userEvent.type(
within(replicationFactorEditForm).getByRole('spinbutton'), within(replicationFactorEditForm).getByRole('spinbutton'),
'4' '4'
); );
userEvent.click(within(replicationFactorEditForm).getByRole('button')); await userEvent.click(
within(replicationFactorEditForm).getByRole('button')
);
await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument()); await waitFor(() => expect(screen.getByRole('dialog')).toBeInTheDocument());
await waitFor(() => clickOnDialogSubmitButton()); await waitFor(() => clickOnDialogSubmitButton());
@ -139,19 +143,19 @@ describe('DangerZone', () => {
const partitionInputSubmitBtn = screen.getAllByText(/submit/i)[0]; const partitionInputSubmitBtn = screen.getAllByText(/submit/i)[0];
const value = (defaultPartitions - 4).toString(); const value = (defaultPartitions - 4).toString();
expect(partitionInputSubmitBtn).toBeDisabled(); expect(partitionInputSubmitBtn).toBeDisabled();
await act(() => { await act(async () => {
userEvent.clear(partitionInput); await userEvent.clear(partitionInput);
userEvent.type(partitionInput, value); await userEvent.type(partitionInput, value);
}); });
expect(partitionInput).toHaveValue(+value); expect(partitionInput).toHaveValue(+value);
expect(partitionInputSubmitBtn).toBeEnabled(); expect(partitionInputSubmitBtn).toBeEnabled();
await act(() => { await act(async () => {
userEvent.click(partitionInputSubmitBtn); await userEvent.click(partitionInputSubmitBtn);
}); });
expect( expect(
screen.getByText(/You can only increase the number of partitions!/i) screen.getByText(/You can only increase the number of partitions!/i)
).toBeInTheDocument(); ).toBeInTheDocument();
userEvent.clear(partitionInput); await userEvent.clear(partitionInput);
await waitFor(() => await waitFor(() =>
expect(screen.getByText(/are required/i)).toBeInTheDocument() expect(screen.getByText(/are required/i)).toBeInTheDocument()
); );
@ -166,11 +170,11 @@ describe('DangerZone', () => {
await waitFor(() => userEvent.clear(replicatorFactorInput)); await waitFor(() => userEvent.clear(replicatorFactorInput));
expect(replicatorFactorInputSubmitBtn).toBeEnabled(); expect(replicatorFactorInputSubmitBtn).toBeEnabled();
userEvent.click(replicatorFactorInputSubmitBtn); await userEvent.click(replicatorFactorInputSubmitBtn);
await waitFor(() => await waitFor(() =>
expect(screen.getByText(/are required/i)).toBeInTheDocument() expect(screen.getByText(/are required/i)).toBeInTheDocument()
); );
userEvent.type(replicatorFactorInput, '1'); await userEvent.type(replicatorFactorInput, '1');
await waitFor(() => await waitFor(() =>
expect(screen.queryByText(/are required/i)).not.toBeInTheDocument() expect(screen.queryByText(/are required/i)).not.toBeInTheDocument()
); );
@ -182,9 +186,9 @@ describe('DangerZone', () => {
const partitionInput = screen.getByPlaceholderText('Number of partitions'); const partitionInput = screen.getByPlaceholderText('Number of partitions');
const partitionInputSubmitBtn = screen.getAllByText(/submit/i)[0]; const partitionInputSubmitBtn = screen.getAllByText(/submit/i)[0];
await act(() => { await act(async () => {
userEvent.type(partitionInput, '5'); await userEvent.type(partitionInput, '5');
userEvent.click(partitionInputSubmitBtn); await userEvent.click(partitionInputSubmitBtn);
}); });
await checkDialogThenPressCancel(); await checkDialogThenPressCancel();
@ -196,9 +200,9 @@ describe('DangerZone', () => {
screen.getByPlaceholderText('Replication Factor'); screen.getByPlaceholderText('Replication Factor');
const replicatorFactorInputSubmitBtn = screen.getAllByText(/submit/i)[1]; const replicatorFactorInputSubmitBtn = screen.getAllByText(/submit/i)[1];
await act(() => { await act(async () => {
userEvent.type(replicatorFactorInput, '5'); await userEvent.type(replicatorFactorInput, '5');
userEvent.click(replicatorFactorInputSubmitBtn); await userEvent.click(replicatorFactorInputSubmitBtn);
}); });
await checkDialogThenPressCancel(); await checkDialogThenPressCancel();

View file

@ -15,16 +15,18 @@ describe('AddEditFilterContainer component', () => {
code: 'mockCode', code: 'mockCode',
}; };
const renderComponent = ( const renderComponent = async (
props: Partial<AddEditFilterContainerProps> = {} props: Partial<AddEditFilterContainerProps> = {}
) => { ) => {
render( await act(() => {
<AddEditFilterContainer render(
cancelBtnHandler={jest.fn()} <AddEditFilterContainer
submitBtnText={props.submitBtnText || defaultSubmitBtn} cancelBtnHandler={jest.fn()}
{...props} submitBtnText={props.submitBtnText || defaultSubmitBtn}
/> {...props}
); />
);
});
}; };
describe('default Component Parameters', () => { describe('default Component Parameters', () => {
@ -43,35 +45,32 @@ describe('AddEditFilterContainer component', () => {
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole('textbox');
const textAreaElement = inputs[0] as HTMLTextAreaElement; const textAreaElement = inputs[0] as HTMLTextAreaElement;
await act(() => textAreaElement.focus();
userEvent.paste(textAreaElement, 'Hello World With TextArea') await userEvent.paste('Hello World With TextArea');
);
const inputNameElement = inputs[1]; const inputNameElement = inputs[1] as HTMLTextAreaElement;
await act(() => userEvent.type(inputNameElement, 'Hello World!')); await userEvent.type(inputNameElement, 'Hello World!');
expect(submitButtonElem).toBeEnabled(); expect(submitButtonElem).toBeEnabled();
await act(() => userEvent.clear(inputNameElement)); await userEvent.clear(inputNameElement);
await userEvent.tab();
expect(submitButtonElem).toBeDisabled(); expect(submitButtonElem).toBeDisabled();
}); });
it('should view the error message after typing and clearing the input', async () => { it('should view the error message after typing and clearing the input', async () => {
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole('textbox');
const user = userEvent.setup();
const textAreaElement = inputs[0] as HTMLTextAreaElement; const textAreaElement = inputs[0] as HTMLTextAreaElement;
await act(() =>
userEvent.paste(textAreaElement, 'Hello World With TextArea')
);
const inputNameElement = inputs[1]; const inputNameElement = inputs[1];
await act(() => {
userEvent.type(inputNameElement, 'Hello World!');
userEvent.clear(inputNameElement); await user.type(textAreaElement, 'Hello World With TextArea');
userEvent.clear(textAreaElement); await user.type(inputNameElement, 'Hello World!');
});
await user.clear(inputNameElement);
await user.keyboard('{Control>}[KeyA]{/Control}{backspace}');
await user.tab();
expect(screen.getByText(/required field/i)).toBeInTheDocument(); expect(screen.getByText(/required field/i)).toBeInTheDocument();
}); });
@ -79,11 +78,12 @@ describe('AddEditFilterContainer component', () => {
describe('Custom setup for the component', () => { describe('Custom setup for the component', () => {
it('should render the input with default data if they are passed', async () => { it('should render the input with default data if they are passed', async () => {
renderComponent({ await act(() => {
inputDisplayNameDefaultValue: mockData.name, renderComponent({
inputCodeDefaultValue: mockData.code, inputDisplayNameDefaultValue: mockData.name,
inputCodeDefaultValue: mockData.code,
});
}); });
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole('textbox');
const textAreaElement = inputs[0] as HTMLTextAreaElement; const textAreaElement = inputs[0] as HTMLTextAreaElement;
const inputNameElement = inputs[1]; const inputNameElement = inputs[1];
@ -93,44 +93,43 @@ describe('AddEditFilterContainer component', () => {
it('should test whether the cancel callback is being called', async () => { it('should test whether the cancel callback is being called', async () => {
const cancelCallback = jest.fn(); const cancelCallback = jest.fn();
renderComponent({ await act(() =>
cancelBtnHandler: cancelCallback, renderComponent({
}); cancelBtnHandler: cancelCallback,
})
);
const cancelBtnElement = screen.getByText(/cancel/i); const cancelBtnElement = screen.getByText(/cancel/i);
await act(() => userEvent.click(cancelBtnElement)); await userEvent.click(cancelBtnElement);
expect(cancelCallback).toBeCalled(); expect(cancelCallback).toBeCalled();
}); });
it('should test whether the submit Callback is being called', async () => { it('should test whether the submit Callback is being called', async () => {
const submitCallback = jest.fn(); const submitCallback = jest.fn();
renderComponent({ await act(() => renderComponent({ submitCallback }));
submitCallback,
});
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole('textbox');
const textAreaElement = inputs[0] as HTMLTextAreaElement; const textAreaElement = inputs[0] as HTMLTextAreaElement;
userEvent.paste(textAreaElement, 'Hello World With TextArea'); textAreaElement.focus();
await userEvent.paste('Hello World With TextArea');
const inputNameElement = inputs[1]; const inputNameElement = inputs[1];
await act(() => userEvent.type(inputNameElement, 'Hello World!')); await userEvent.type(inputNameElement, 'Hello World!');
const submitBtnElement = screen.getByText(defaultSubmitBtn); const submitBtnElement = screen.getByText(defaultSubmitBtn);
expect(submitBtnElement).toBeEnabled(); expect(submitBtnElement).toBeEnabled();
await act(() => userEvent.click(submitBtnElement)); await userEvent.click(submitBtnElement);
expect(submitCallback).toBeCalled(); expect(submitCallback).toBeCalled();
}); });
it('should display the checkbox if the props is passed and initially check state', async () => { it('should display the checkbox if the props is passed and initially check state', async () => {
renderComponent({ isAdd: true }); await act(() => renderComponent({ isAdd: true }));
const checkbox = screen.getByRole('checkbox'); const checkbox = screen.getByRole('checkbox');
expect(checkbox).toBeInTheDocument(); expect(checkbox).toBeInTheDocument();
expect(checkbox).not.toBeChecked(); expect(checkbox).not.toBeChecked();
await act(() => userEvent.click(checkbox)); await userEvent.click(checkbox);
expect(checkbox).toBeChecked(); expect(checkbox).toBeChecked();
}); });

View file

@ -4,7 +4,7 @@ import AddFilter, {
} from 'components/Topics/Topic/Messages/Filters/AddFilter'; } from 'components/Topics/Topic/Messages/Filters/AddFilter';
import { render } from 'lib/testHelpers'; import { render } from 'lib/testHelpers';
import { MessageFilters } from 'components/Topics/Topic/Messages/Filters/Filters'; import { MessageFilters } from 'components/Topics/Topic/Messages/Filters/Filters';
import { act, screen } from '@testing-library/react'; import { act, fireEvent, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
const filters: MessageFilters[] = [ const filters: MessageFilters[] = [
@ -32,14 +32,12 @@ const renderComponent = (props: Partial<FilterModalProps> = {}) =>
describe('AddFilter component', () => { describe('AddFilter component', () => {
describe('', () => { describe('', () => {
beforeEach(async () => { beforeEach(() => {
await act(() => { renderComponent();
renderComponent();
});
}); });
it('should test click on Saved Filters redirects to Saved components', () => { it('should test click on Saved Filters redirects to Saved components', async () => {
userEvent.click(screen.getByRole('savedFilterText')); await userEvent.click(screen.getByRole('savedFilterText'));
expect(screen.getByText('Saved Filters')).toBeInTheDocument(); expect(screen.getByText('Saved Filters')).toBeInTheDocument();
expect(screen.getByRole('savedFilterText')).toBeInTheDocument(); expect(screen.getByRole('savedFilterText')).toBeInTheDocument();
}); });
@ -48,8 +46,8 @@ describe('AddFilter component', () => {
expect(screen.getByRole('button', { name: 'info' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'info' })).toBeInTheDocument();
}); });
it('renders InfoModal', () => { it('renders InfoModal', async () => {
userEvent.click(screen.getByRole('button', { name: 'info' })); await userEvent.click(screen.getByRole('button', { name: 'info' }));
expect(screen.getByRole('button', { name: 'Ok' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Ok' })).toBeInTheDocument();
expect( expect(
screen.getByRole('list', { name: 'info-list' }) screen.getByRole('list', { name: 'info-list' })
@ -57,7 +55,7 @@ describe('AddFilter component', () => {
}); });
it('should test click on return to custom filter redirects to Saved Filters', async () => { it('should test click on return to custom filter redirects to Saved Filters', async () => {
userEvent.click(screen.getByRole('savedFilterText')); await userEvent.click(screen.getByRole('savedFilterText'));
expect(screen.queryByText('Saved filters')).not.toBeInTheDocument(); expect(screen.queryByText('Saved filters')).not.toBeInTheDocument();
expect(screen.getByRole('savedFilterText')).toBeInTheDocument(); expect(screen.getByRole('savedFilterText')).toBeInTheDocument();
@ -66,9 +64,7 @@ describe('AddFilter component', () => {
describe('Add new filter', () => { describe('Add new filter', () => {
beforeEach(async () => { beforeEach(async () => {
await act(() => { renderComponent();
renderComponent();
});
}); });
it('adding new filter', async () => { it('adding new filter', async () => {
@ -83,9 +79,10 @@ describe('AddFilter component', () => {
expect(addFilterBtn).toBeDisabled(); expect(addFilterBtn).toBeDisabled();
expect(screen.getByPlaceholderText('Enter Name')).toBeInTheDocument(); expect(screen.getByPlaceholderText('Enter Name')).toBeInTheDocument();
await act(() => { await act(async () => {
userEvent.paste(codeTextBox, codeValue); codeTextBox.focus();
userEvent.type(nameTextBox, nameValue); await userEvent.paste(codeValue);
await userEvent.type(nameTextBox, nameValue);
}); });
expect(addFilterBtn).toBeEnabled(); expect(addFilterBtn).toBeEnabled();
@ -101,7 +98,10 @@ describe('AddFilter component', () => {
const addFilterBtn = screen.getByRole('button', { name: /Add filter/i }); const addFilterBtn = screen.getByRole('button', { name: /Add filter/i });
expect(addFilterBtn).toBeDisabled(); expect(addFilterBtn).toBeDisabled();
expect(screen.getByPlaceholderText('Enter Name')).toBeInTheDocument(); expect(screen.getByPlaceholderText('Enter Name')).toBeInTheDocument();
await act(() => userEvent.paste(codeTextBox, code)); await act(async () => {
codeTextBox.focus();
await userEvent.paste(code);
});
expect(addFilterBtn).toBeEnabled(); expect(addFilterBtn).toBeEnabled();
expect(codeTextBox).toHaveValue(`${code}\n\n`); expect(codeTextBox).toHaveValue(`${code}\n\n`);
}); });
@ -110,10 +110,10 @@ describe('AddFilter component', () => {
await act(() => { await act(() => {
renderComponent({ isSavedFiltersOpen: true }); renderComponent({ isSavedFiltersOpen: true });
}); });
userEvent.click(screen.getByText('Saved Filters')); await userEvent.click(screen.getByText('Saved Filters'));
const index = 0; const index = 0;
const editButton = screen.getAllByText('Edit')[index]; const editButton = screen.getAllByText('Edit')[index];
userEvent.click(editButton); await userEvent.click(editButton);
const { code, name } = filters[index]; const { code, name } = filters[index];
expect(editFilterMock).toHaveBeenCalledTimes(1); expect(editFilterMock).toHaveBeenCalledTimes(1);
expect(editFilterMock).toHaveBeenCalledWith({ expect(editFilterMock).toHaveBeenCalledWith({
@ -133,12 +133,10 @@ describe('AddFilter component', () => {
const nameValue = 'filter name'; const nameValue = 'filter name';
beforeEach(async () => { beforeEach(async () => {
await act(() => { await renderComponent({
renderComponent({ addFilter: addFilterMock,
addFilter: addFilterMock, activeFilterHandler: activeFilterHandlerMock,
activeFilterHandler: activeFilterHandlerMock, toggleIsOpen: toggleModelMock,
toggleIsOpen: toggleModelMock,
});
}); });
}); });
@ -150,12 +148,14 @@ describe('AddFilter component', () => {
describe('OnSubmit conditions with codeValue and nameValue in fields', () => { describe('OnSubmit conditions with codeValue and nameValue in fields', () => {
beforeEach(async () => { beforeEach(async () => {
await act(() => { const textAreaElement = screen.getAllByRole(
userEvent.paste( 'textbox'
screen.getAllByRole('textbox')[0] as HTMLTextAreaElement, )[0] as HTMLTextAreaElement;
codeValue const input = screen.getAllByRole('textbox')[1];
); await act(async () => {
userEvent.type(screen.getAllByRole('textbox')[1], nameValue); textAreaElement.focus();
await userEvent.paste(codeValue);
await userEvent.type(input, nameValue);
}); });
}); });
@ -166,16 +166,18 @@ describe('AddFilter component', () => {
}); });
expect(addFilterBtn).toBeEnabled(); expect(addFilterBtn).toBeEnabled();
await act(() => userEvent.click(addFilterBtn)); await act(async () => {
await userEvent.click(addFilterBtn);
});
expect(activeFilterHandlerMock).toHaveBeenCalled(); expect(activeFilterHandlerMock).toHaveBeenCalled();
expect(addFilterMock).not.toHaveBeenCalled(); expect(addFilterMock).not.toHaveBeenCalled();
}); });
it('OnSubmit condition with checkbox on functionality', async () => { it('OnSubmit condition with checkbox on functionality', async () => {
await act(() => { await act(async () => {
userEvent.click(screen.getByRole('checkbox')); await userEvent.click(screen.getByRole('checkbox'));
userEvent.click(screen.getAllByRole('button')[2]); await userEvent.click(screen.getAllByRole('button')[2]);
}); });
expect(activeFilterHandlerMock).not.toHaveBeenCalled(); expect(activeFilterHandlerMock).not.toHaveBeenCalled();
@ -193,11 +195,15 @@ describe('AddFilter component', () => {
name: /Add filter/i, name: /Add filter/i,
}); });
await act(() => userEvent.clear(nameTextBox)); await act(async () => {
await userEvent.clear(nameTextBox);
});
expect(nameTextBox).toHaveValue(''); expect(nameTextBox).toHaveValue('');
await act(() => userEvent.click(addFilterBtn)); await act(async () => {
await userEvent.click(addFilterBtn);
});
expect(activeFilterHandlerMock).toHaveBeenCalledTimes(1); expect(activeFilterHandlerMock).toHaveBeenCalledTimes(1);
expect(activeFilterHandlerMock).toHaveBeenCalledWith( expect(activeFilterHandlerMock).toHaveBeenCalledWith(
@ -211,17 +217,25 @@ describe('AddFilter component', () => {
// get reset-ed // get reset-ed
expect(codeTextBox).toHaveValue(``); expect(codeTextBox).toHaveValue(``);
expect(toggleModelMock).toHaveBeenCalled(); expect(toggleModelMock).toHaveBeenCalled();
codeTextBox.focus();
await act(() => userEvent.paste(codeTextBox, codeValue)); await act(async () => {
await userEvent.paste(codeValue);
});
expect(codeTextBox).toHaveValue(`${codeValue}\n\n`); expect(codeTextBox).toHaveValue(`${codeValue}\n\n`);
await act(() => userEvent.click(checkbox)); await act(async () => {
await userEvent.click(checkbox);
});
expect(addFilterBtn).toBeDisabled(); expect(addFilterBtn).toBeDisabled();
await act(() => userEvent.type(nameTextBox, nameValue)); await act(async () => {
await userEvent.type(nameTextBox, nameValue);
});
expect(nameTextBox).toHaveValue(nameValue); expect(nameTextBox).toHaveValue(nameValue);
expect(addFilterBtn).toBeEnabled(); expect(addFilterBtn).toBeEnabled();
await act(() => userEvent.click(addFilterBtn)); await act(async () => {
await userEvent.click(addFilterBtn);
});
expect(activeFilterHandlerMock).toHaveBeenCalledTimes(1); expect(activeFilterHandlerMock).toHaveBeenCalledTimes(1);
expect(addFilterMock).toHaveBeenCalledWith({ expect(addFilterMock).toHaveBeenCalledWith({
@ -238,16 +252,23 @@ describe('AddFilter component', () => {
)[0] as HTMLTextAreaElement; )[0] as HTMLTextAreaElement;
const nameTextBox = screen.getAllByRole('textbox')[1]; const nameTextBox = screen.getAllByRole('textbox')[1];
const addFilterBtn = screen.getByRole('button', { name: /Add filter/i }); const addFilterBtn = screen.getByRole('button', { name: /Add filter/i });
await act(() => { act(() => {
userEvent.clear(nameTextBox); // await userEvent.clear(nameTextBox);
userEvent.clear(codeTextBox); // codeTextBox.focus();
userEvent.paste(codeTextBox, longCodeValue); // await userEvent.clear(codeTextBox);
fireEvent.input(nameTextBox, {
inputType: '',
});
fireEvent.input(codeTextBox, {
inputType: '',
});
}); });
codeTextBox.focus();
await userEvent.paste(longCodeValue);
expect(nameTextBox).toHaveValue(''); expect(nameTextBox).toHaveValue('');
expect(codeTextBox).toHaveValue(`${longCodeValue}\n\n`); expect(codeTextBox).toHaveValue(`${longCodeValue}\n\n`);
await act(() => userEvent.click(addFilterBtn)); await userEvent.click(addFilterBtn);
const filterName = `${longCodeValue.slice(0, 16)}...`; const filterName = `${longCodeValue.slice(0, 16)}...`;

View file

@ -35,7 +35,7 @@ describe('EditFilter component', () => {
await act(() => { await act(() => {
renderComponent({ toggleEditModal }); renderComponent({ toggleEditModal });
}); });
userEvent.click(screen.getByRole('button', { name: /Cancel/i })); await userEvent.click(screen.getByRole('button', { name: /Cancel/i }));
expect(toggleEditModal).toHaveBeenCalledTimes(1); expect(toggleEditModal).toHaveBeenCalledTimes(1);
}); });
@ -43,16 +43,16 @@ describe('EditFilter component', () => {
const toggleEditModal = jest.fn(); const toggleEditModal = jest.fn();
const editSavedFilter = jest.fn(); const editSavedFilter = jest.fn();
await act(() => { await renderComponent({ toggleEditModal, editSavedFilter });
renderComponent({ toggleEditModal, editSavedFilter });
});
const inputs = screen.getAllByRole('textbox'); const inputs = screen.getAllByRole('textbox');
const textAreaElement = inputs[0] as HTMLTextAreaElement; const textAreaElement = inputs[0] as HTMLTextAreaElement;
const inputNameElement = inputs[1]; const inputNameElement = inputs[1];
await act(() => { await act(async () => {
userEvent.paste(textAreaElement, 'edited code'); textAreaElement.focus();
userEvent.type(inputNameElement, 'edited name'); await userEvent.paste('edited code');
textAreaElement.focus();
await userEvent.type(inputNameElement, 'edited name');
fireEvent.submit(screen.getByRole('form')); fireEvent.submit(screen.getByRole('form'));
}); });
expect(toggleEditModal).toHaveBeenCalledTimes(1); expect(toggleEditModal).toHaveBeenCalledTimes(1);

View file

@ -32,9 +32,9 @@ describe('FilterModal component', () => {
screen.getByRole('heading', { name: /add filter/i, level: 3 }) screen.getByRole('heading', { name: /add filter/i, level: 3 })
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it('renders component with edit filter modal', () => { it('renders component with edit filter modal', async () => {
userEvent.click(screen.getByRole('savedFilterText')); await userEvent.click(screen.getByRole('savedFilterText'));
userEvent.click(screen.getByText('Edit')); await userEvent.click(screen.getByText('Edit'));
expect( expect(
screen.getByRole('heading', { name: /edit saved filter/i, level: 3 }) screen.getByRole('heading', { name: /edit saved filter/i, level: 3 })
).toBeInTheDocument(); ).toBeInTheDocument();

View file

@ -92,17 +92,17 @@ describe('Filters component', () => {
}); });
}); });
it('search input', () => { it('search input', async () => {
const searchInput = screen.getByPlaceholderText('Search'); const searchInput = screen.getByPlaceholderText('Search');
expect(searchInput).toHaveValue(''); expect(searchInput).toHaveValue('');
userEvent.type(searchInput, inputValue); await userEvent.type(searchInput, inputValue);
expect(searchInput).toHaveValue(inputValue); expect(searchInput).toHaveValue(inputValue);
}); });
it('offset input', () => { it('offset input', async () => {
const offsetInput = screen.getByPlaceholderText('Offset'); const offsetInput = screen.getByPlaceholderText('Offset');
expect(offsetInput).toHaveValue(''); expect(offsetInput).toHaveValue('');
userEvent.type(offsetInput, inputValue); await userEvent.type(offsetInput, inputValue);
expect(offsetInput).toHaveValue(inputValue); expect(offsetInput).toHaveValue(inputValue);
}); });
@ -110,10 +110,12 @@ describe('Filters component', () => {
const seekTypeSelect = screen.getAllByRole('listbox'); const seekTypeSelect = screen.getAllByRole('listbox');
const option = screen.getAllByRole('option'); const option = screen.getAllByRole('option');
await act(() => userEvent.click(seekTypeSelect[0])); await act(async () => {
await userEvent.click(seekTypeSelect[0]);
});
await act(() => { await act(async () => {
userEvent.selectOptions(seekTypeSelect[0], ['Timestamp']); await userEvent.selectOptions(seekTypeSelect[0], ['Timestamp']);
}); });
expect(option[0]).toHaveTextContent('Timestamp'); expect(option[0]).toHaveTextContent('Timestamp');
@ -142,26 +144,28 @@ describe('Filters component', () => {
options = screen.getAllByRole('option'); options = screen.getAllByRole('option');
}); });
it('seekType select', () => { it('seekType select', async () => {
expect(options[0]).toHaveTextContent('Offset'); expect(options[0]).toHaveTextContent('Offset');
userEvent.click(seekTypeSelects[0]); await userEvent.click(seekTypeSelects[0]);
userEvent.selectOptions(seekTypeSelects[0], [mockTypeOptionSelectLabel]); await userEvent.selectOptions(seekTypeSelects[0], [
mockTypeOptionSelectLabel,
]);
expect(options[0]).toHaveTextContent(mockTypeOptionSelectLabel); expect(options[0]).toHaveTextContent(mockTypeOptionSelectLabel);
expect(screen.getByText('Submit')).toBeInTheDocument(); expect(screen.getByText('Submit')).toBeInTheDocument();
}); });
it('seekDirection select', () => { it('seekDirection select', async () => {
userEvent.click(seekTypeSelects[3]); await userEvent.click(seekTypeSelects[3]);
userEvent.selectOptions(seekTypeSelects[3], [ await userEvent.selectOptions(seekTypeSelects[3], [
mockDirectionOptionSelectLabel, mockDirectionOptionSelectLabel,
]); ]);
expect(options[3]).toHaveTextContent(mockDirectionOptionSelectLabel); expect(options[3]).toHaveTextContent(mockDirectionOptionSelectLabel);
}); });
}); });
it('stop loading when live mode is active', () => { it('stop loading when live mode is active', async () => {
renderComponent(); renderComponent();
userEvent.click(screen.getByText('Stop loading')); await userEvent.click(screen.getByText('Stop loading'));
const option = screen.getAllByRole('option'); const option = screen.getAllByRole('option');
expect(option[3]).toHaveTextContent('Oldest First'); expect(option[3]).toHaveTextContent('Oldest First');
expect(screen.getByText('Submit')).toBeInTheDocument(); expect(screen.getByText('Submit')).toBeInTheDocument();
@ -169,13 +173,13 @@ describe('Filters component', () => {
it('renders addFilter modal', async () => { it('renders addFilter modal', async () => {
renderComponent(); renderComponent();
await act(() => await act(async () => {
userEvent.click( await userEvent.click(
screen.getByRole('button', { screen.getByRole('button', {
name: /add filters/i, name: /add filters/i,
}) })
) );
); });
expect(screen.getByTestId('messageFilterModal')).toBeInTheDocument(); expect(screen.getByTestId('messageFilterModal')).toBeInTheDocument();
}); });
@ -183,13 +187,13 @@ describe('Filters component', () => {
beforeEach(async () => { beforeEach(async () => {
renderComponent(); renderComponent();
await act(() => await act(async () => {
userEvent.click( await userEvent.click(
screen.getByRole('button', { screen.getByRole('button', {
name: /add filters/i, name: /add filters/i,
}) })
) );
); });
const filterName = 'filter name'; const filterName = 'filter name';
const filterCode = 'filter code'; const filterCode = 'filter code';
@ -201,21 +205,22 @@ describe('Filters component', () => {
const textAreaElement = textBoxElements[0] as HTMLTextAreaElement; const textAreaElement = textBoxElements[0] as HTMLTextAreaElement;
const inputNameElement = textBoxElements[1]; const inputNameElement = textBoxElements[1];
await act(() => { await act(async () => {
userEvent.paste(textAreaElement, filterName); textAreaElement.focus();
userEvent.type(inputNameElement, filterCode); await userEvent.paste(filterName);
await userEvent.type(inputNameElement, filterCode);
}); });
expect(textAreaElement.value).toEqual(`${filterName}\n\n`); expect(textAreaElement.value).toEqual(`${filterName}\n\n`);
expect(inputNameElement).toHaveValue(filterCode); expect(inputNameElement).toHaveValue(filterCode);
await act(() => await act(async () => {
userEvent.click( await userEvent.click(
within(messageFilterModal).getByRole('button', { within(messageFilterModal).getByRole('button', {
name: /add filter/i, name: /add filter/i,
}) })
) );
); });
}); });
it('shows saved smart filter', () => { it('shows saved smart filter', () => {
@ -225,7 +230,9 @@ describe('Filters component', () => {
it('delete the active smart Filter', async () => { it('delete the active smart Filter', async () => {
const smartFilterElement = screen.getByTestId('activeSmartFilter'); const smartFilterElement = screen.getByTestId('activeSmartFilter');
const deleteIcon = within(smartFilterElement).getByText('mock-CloseIcon'); const deleteIcon = within(smartFilterElement).getByText('mock-CloseIcon');
await act(() => userEvent.click(deleteIcon)); await act(async () => {
await userEvent.click(deleteIcon);
});
const anotherSmartFilterElement = const anotherSmartFilterElement =
screen.queryByTestId('activeSmartFilter'); screen.queryByTestId('activeSmartFilter');

View file

@ -5,10 +5,10 @@ import React from 'react';
import InfoModal from 'components/Topics/Topic/Messages/Filters/InfoModal'; import InfoModal from 'components/Topics/Topic/Messages/Filters/InfoModal';
describe('InfoModal component', () => { describe('InfoModal component', () => {
it('closes InfoModal', () => { it('closes InfoModal', async () => {
const toggleInfoModal = jest.fn(); const toggleInfoModal = jest.fn();
render(<InfoModal toggleIsOpen={toggleInfoModal} />); render(<InfoModal toggleIsOpen={toggleInfoModal} />);
userEvent.click(screen.getByRole('button', { name: 'Ok' })); await userEvent.click(screen.getByRole('button', { name: 'Ok' }));
expect(toggleInfoModal).toHaveBeenCalledTimes(1); expect(toggleInfoModal).toHaveBeenCalledTimes(1);
}); });
}); });

View file

@ -3,12 +3,7 @@ import SavedFilters, {
Props, Props,
} from 'components/Topics/Topic/Messages/Filters/SavedFilters'; } from 'components/Topics/Topic/Messages/Filters/SavedFilters';
import { MessageFilters } from 'components/Topics/Topic/Messages/Filters/Filters'; import { MessageFilters } from 'components/Topics/Topic/Messages/Filters/Filters';
import { import { screen, waitFor, within } from '@testing-library/react';
screen,
waitFor,
waitForElementToBeRemoved,
within,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { render } from 'lib/testHelpers'; import { render } from 'lib/testHelpers';
@ -35,17 +30,17 @@ describe('SavedFilter Component', () => {
const getSavedFilters = () => screen.getAllByRole('savedFilter'); const getSavedFilters = () => screen.getAllByRole('savedFilter');
it('should check the Cancel button click', () => { it('should check the Cancel button click', async () => {
const cancelMock = jest.fn(); const cancelMock = jest.fn();
setUpComponent({ closeModal: cancelMock }); setUpComponent({ closeModal: cancelMock });
userEvent.click(screen.getByText(/cancel/i)); await userEvent.click(screen.getByText(/cancel/i));
expect(cancelMock).toHaveBeenCalled(); expect(cancelMock).toHaveBeenCalled();
}); });
it('should check on go back button click', () => { it('should check on go back button click', async () => {
const onGoBackMock = jest.fn(); const onGoBackMock = jest.fn();
setUpComponent({ onGoBack: onGoBackMock }); setUpComponent({ onGoBack: onGoBackMock });
userEvent.click(screen.getByText(/back to create filters/i)); await userEvent.click(screen.getByText(/back to create filters/i));
expect(onGoBackMock).toHaveBeenCalled(); expect(onGoBackMock).toHaveBeenCalled();
}); });
@ -84,26 +79,26 @@ describe('SavedFilter Component', () => {
expect(screen.getByText(mockFilters[1].name)).toBeInTheDocument(); expect(screen.getByText(mockFilters[1].name)).toBeInTheDocument();
}); });
it('should check the Filter edit Button works', () => { it('should check the Filter edit Button works', async () => {
const savedFilters = getSavedFilters(); const savedFilters = getSavedFilters();
userEvent.hover(savedFilters[0]); await userEvent.hover(savedFilters[0]);
userEvent.click(within(savedFilters[0]).getByText(/edit/i)); await userEvent.click(within(savedFilters[0]).getByText(/edit/i));
expect(onEditMock).toHaveBeenCalled(); expect(onEditMock).toHaveBeenCalled();
userEvent.hover(savedFilters[1]); await userEvent.hover(savedFilters[1]);
userEvent.click(within(savedFilters[1]).getByText(/edit/i)); await userEvent.click(within(savedFilters[1]).getByText(/edit/i));
expect(onEditMock).toHaveBeenCalledTimes(2); expect(onEditMock).toHaveBeenCalledTimes(2);
}); });
it('should check the select filter', () => { it('should check the select filter', async () => {
const selectFilterButton = screen.getByText(/Select filter/i); const selectFilterButton = screen.getByText(/Select filter/i);
userEvent.click(selectFilterButton); await userEvent.click(selectFilterButton);
expect(activeFilterMock).not.toHaveBeenCalled(); expect(activeFilterMock).not.toHaveBeenCalled();
const savedFilterElement = getSavedFilters(); const savedFilterElement = getSavedFilters();
userEvent.click(savedFilterElement[0]); await userEvent.click(savedFilterElement[0]);
userEvent.click(selectFilterButton); await userEvent.click(selectFilterButton);
expect(activeFilterMock).toHaveBeenCalled(); expect(activeFilterMock).toHaveBeenCalled();
expect(cancelMock).toHaveBeenCalled(); expect(cancelMock).toHaveBeenCalled();
@ -121,12 +116,12 @@ describe('SavedFilter Component', () => {
deleteMock.mockClear(); deleteMock.mockClear();
}); });
it('Open Confirmation for the deletion modal', () => { it('Open Confirmation for the deletion modal', async () => {
setUpComponent({ deleteFilter: deleteMock }); setUpComponent({ deleteFilter: deleteMock });
const savedFilters = getSavedFilters(); const savedFilters = getSavedFilters();
const deleteIcons = screen.getAllByText('mock-DeleteIcon'); const deleteIcons = screen.getAllByText('mock-DeleteIcon');
userEvent.hover(savedFilters[0]); await userEvent.hover(savedFilters[0]);
userEvent.click(deleteIcons[0]); await userEvent.click(deleteIcons[0]);
const modelDialog = screen.getByRole('dialog'); const modelDialog = screen.getByRole('dialog');
expect(modelDialog).toBeInTheDocument(); expect(modelDialog).toBeInTheDocument();
expect( expect(
@ -139,8 +134,8 @@ describe('SavedFilter Component', () => {
const savedFilters = getSavedFilters(); const savedFilters = getSavedFilters();
const deleteIcons = screen.getAllByText('mock-DeleteIcon'); const deleteIcons = screen.getAllByText('mock-DeleteIcon');
userEvent.hover(savedFilters[0]); await userEvent.hover(savedFilters[0]);
userEvent.click(deleteIcons[0]); await userEvent.click(deleteIcons[0]);
const modelDialog = screen.getByRole('dialog'); const modelDialog = screen.getByRole('dialog');
expect(modelDialog).toBeInTheDocument(); expect(modelDialog).toBeInTheDocument();
@ -156,14 +151,13 @@ describe('SavedFilter Component', () => {
const savedFilters = getSavedFilters(); const savedFilters = getSavedFilters();
const deleteIcons = screen.getAllByText('mock-DeleteIcon'); const deleteIcons = screen.getAllByText('mock-DeleteIcon');
userEvent.hover(savedFilters[0]); await userEvent.hover(savedFilters[0]);
userEvent.click(deleteIcons[0]); await userEvent.click(deleteIcons[0]);
await waitFor(() => expect(screen.queryByRole('dialog')).toBeInTheDocument();
userEvent.click(screen.getByRole('button', { name: 'Confirm' })) await userEvent.click(screen.getByRole('button', { name: 'Confirm' }));
);
expect(deleteMock).toHaveBeenCalledTimes(1); expect(deleteMock).toHaveBeenCalledTimes(1);
await waitForElementToBeRemoved(() => screen.queryByRole('dialog')); expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
}); });
}); });
}); });

View file

@ -50,9 +50,9 @@ describe('MessageContent screen', () => {
}); });
describe('when switched to display the key', () => { describe('when switched to display the key', () => {
it('makes key tab active', () => { it('makes key tab active', async () => {
const keyTab = screen.getAllByText('Key'); const keyTab = screen.getAllByText('Key');
userEvent.click(keyTab[0]); await userEvent.click(keyTab[0]);
expect(keyTab[0]).toHaveStyleRule( expect(keyTab[0]).toHaveStyleRule(
'background-color', 'background-color',
theme.secondaryTab.backgroundColor.active theme.secondaryTab.backgroundColor.active
@ -61,8 +61,8 @@ describe('MessageContent screen', () => {
}); });
describe('when switched to display the headers', () => { describe('when switched to display the headers', () => {
it('makes headers tab active', () => { it('makes Headers tab active', async () => {
userEvent.click(screen.getByText('Headers')); await userEvent.click(screen.getByText('Headers'));
expect(screen.getByText('Headers')).toHaveStyleRule( expect(screen.getByText('Headers')).toHaveStyleRule(
'background-color', 'background-color',
theme.secondaryTab.backgroundColor.active theme.secondaryTab.backgroundColor.active
@ -71,9 +71,9 @@ describe('MessageContent screen', () => {
}); });
describe('when switched to display the value', () => { describe('when switched to display the value', () => {
it('makes value tab active', () => { it('makes value tab active', async () => {
const contentTab = screen.getAllByText('Value'); const contentTab = screen.getAllByText('Value');
userEvent.click(contentTab[0]); await userEvent.click(contentTab[0]);
expect(contentTab[0]).toHaveStyleRule( expect(contentTab[0]).toHaveStyleRule(
'background-color', 'background-color',
theme.secondaryTab.backgroundColor.active theme.secondaryTab.backgroundColor.active

View file

@ -66,24 +66,24 @@ describe('Message component', () => {
).not.toBeInTheDocument(); ).not.toBeInTheDocument();
}); });
it('should check the dropdown being visible during hover', () => { it('should check the dropdown being visible during hover', async () => {
renderComponent(); renderComponent();
const text = 'Save as a file'; const text = 'Save as a file';
const trElement = screen.getByRole('row'); const trElement = screen.getByRole('row');
expect(screen.queryByText(text)).not.toBeInTheDocument(); expect(screen.queryByText(text)).not.toBeInTheDocument();
userEvent.hover(trElement); await userEvent.hover(trElement);
expect(screen.getByText(text)).toBeInTheDocument(); expect(screen.getByText(text)).toBeInTheDocument();
userEvent.unhover(trElement); await userEvent.unhover(trElement);
expect(screen.queryByText(text)).not.toBeInTheDocument(); expect(screen.queryByText(text)).not.toBeInTheDocument();
}); });
it('should check open Message Content functionality', () => { it('should check open Message Content functionality', async () => {
renderComponent(); renderComponent();
const messageToggleIcon = screen.getByRole('button', { hidden: true }); const messageToggleIcon = screen.getByRole('button', { hidden: true });
expect(screen.queryByText(messageContentText)).not.toBeInTheDocument(); expect(screen.queryByText(messageContentText)).not.toBeInTheDocument();
userEvent.click(messageToggleIcon); await userEvent.click(messageToggleIcon);
expect(screen.getByText(messageContentText)).toBeInTheDocument(); expect(screen.getByText(messageContentText)).toBeInTheDocument();
}); });
}); });

View file

@ -57,24 +57,24 @@ describe('Messages', () => {
); );
const labelValue1 = SeekDirectionOptions[1].label; const labelValue1 = SeekDirectionOptions[1].label;
userEvent.click(seekDirectionSelect); await userEvent.click(seekDirectionSelect);
userEvent.selectOptions(seekDirectionSelect, [labelValue1]); await userEvent.selectOptions(seekDirectionSelect, [labelValue1]);
expect(seekDirectionOption).toHaveTextContent(labelValue1); expect(seekDirectionOption).toHaveTextContent(labelValue1);
const labelValue0 = SeekDirectionOptions[0].label; const labelValue0 = SeekDirectionOptions[0].label;
userEvent.click(seekDirectionSelect); await userEvent.click(seekDirectionSelect);
userEvent.selectOptions(seekDirectionSelect, [labelValue0]); await userEvent.selectOptions(seekDirectionSelect, [labelValue0]);
expect(seekDirectionOption).toHaveTextContent(labelValue0); expect(seekDirectionOption).toHaveTextContent(labelValue0);
const liveOptionConf = SeekDirectionOptions[2]; const liveOptionConf = SeekDirectionOptions[2];
const labelValue2 = liveOptionConf.label; const labelValue2 = liveOptionConf.label;
userEvent.click(seekDirectionSelect); await userEvent.click(seekDirectionSelect);
const liveModeLi = screen.getByRole( const liveModeLi = screen.getByRole(
(role, element) => (role, element) =>
role === 'option' && role === 'option' &&
element?.getAttribute('value') === liveOptionConf.value element?.getAttribute('value') === liveOptionConf.value
); );
userEvent.selectOptions(seekDirectionSelect, [liveModeLi]); await userEvent.selectOptions(seekDirectionSelect, [liveModeLi]);
expect(seekDirectionOption).toHaveTextContent(labelValue2); expect(seekDirectionOption).toHaveTextContent(labelValue2);
await waitFor(() => { await waitFor(() => {

View file

@ -109,14 +109,14 @@ describe('Overview', () => {
}); });
describe('when Clear Messages is clicked', () => { describe('when Clear Messages is clicked', () => {
it('should when Clear Messages is clicked', () => { it('should when Clear Messages is clicked', async () => {
renderComponent({ renderComponent({
...externalTopicPayload, ...externalTopicPayload,
cleanUpPolicy: CleanUpPolicy.DELETE, cleanUpPolicy: CleanUpPolicy.DELETE,
}); });
const clearMessagesButton = screen.getByText('Clear Messages'); const clearMessagesButton = screen.getByText('Clear Messages');
userEvent.click(clearMessagesButton); await userEvent.click(clearMessagesButton);
expect(uwrapMock).toHaveBeenCalledTimes(1); expect(uwrapMock).toHaveBeenCalledTimes(1);
}); });
}); });

View file

@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import SendMessage from 'components/Topics/Topic/SendMessage/SendMessage'; import SendMessage from 'components/Topics/Topic/SendMessage/SendMessage';
import { act, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { render, WithRoute } from 'lib/testHelpers'; import { render, WithRoute } from 'lib/testHelpers';
import { clusterTopicPath } from 'lib/paths'; import { clusterTopicPath } from 'lib/paths';
@ -47,32 +47,26 @@ const mockOnSubmit = jest.fn();
const renderComponent = async () => { const renderComponent = async () => {
const path = clusterTopicPath(clusterName, topicName); const path = clusterTopicPath(clusterName, topicName);
await act(() => { await render(
render( <WithRoute path={clusterTopicPath()}>
<WithRoute path={clusterTopicPath()}> <SendMessage onSubmit={mockOnSubmit} />
<SendMessage onSubmit={mockOnSubmit} /> </WithRoute>,
</WithRoute>, { initialEntries: [path] }
{ initialEntries: [path] } );
);
});
}; };
const renderAndSubmitData = async (error: string[] = []) => { const renderAndSubmitData = async (error: string[] = []) => {
await renderComponent(); await renderComponent();
await act(() => { await userEvent.click(screen.getAllByRole('listbox')[0]);
userEvent.click(screen.getAllByRole('listbox')[0]);
}); await userEvent.click(screen.getAllByRole('option')[1]);
await act(() => {
userEvent.click(screen.getAllByRole('option')[1]);
});
(validateBySchema as Mock).mockImplementation(() => error); (validateBySchema as Mock).mockImplementation(() => error);
const submitButton = screen.getByRole('button', { const submitButton = screen.getByRole('button', {
name: 'Produce Message', name: 'Produce Message',
}); });
await waitFor(() => expect(submitButton).toBeEnabled()); await waitFor(() => expect(submitButton).toBeEnabled());
await act(() => { await userEvent.click(submitButton);
userEvent.click(submitButton);
});
}; };
describe('SendMessage', () => { describe('SendMessage', () => {

View file

@ -50,10 +50,10 @@ describe('Metrics', () => {
renderComponent(); renderComponent();
}); });
it('renders Stop Analysis button', () => { it('renders Stop Analysis button', async () => {
const btn = screen.getByRole('button', { name: 'Stop Analysis' }); const btn = screen.getByRole('button', { name: 'Stop Analysis' });
expect(btn).toBeInTheDocument(); expect(btn).toBeInTheDocument();
userEvent.click(btn); await userEvent.click(btn);
expect(cancelMock).toHaveBeenCalled(); expect(cancelMock).toHaveBeenCalled();
}); });
@ -95,9 +95,9 @@ describe('Metrics', () => {
expect(btns.length).toEqual(2); expect(btns.length).toEqual(2);
expect(screen.queryByText('Partition stats')).not.toBeInTheDocument(); expect(screen.queryByText('Partition stats')).not.toBeInTheDocument();
userEvent.click(btns[0]); await userEvent.click(btns[0]);
expect(screen.getAllByText('Partition stats').length).toEqual(1); expect(screen.getAllByText('Partition stats').length).toEqual(1);
userEvent.click(btns[1]); await userEvent.click(btns[1]);
expect(screen.getAllByText('Partition stats').length).toEqual(2); expect(screen.getAllByText('Partition stats').length).toEqual(2);
}); });
}); });

View file

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { act, screen, waitFor } from '@testing-library/react'; import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import ClusterContext from 'components/contexts/ClusterContext'; import ClusterContext from 'components/contexts/ClusterContext';
import Details from 'components/Topics/Topic/Topic'; import Details from 'components/Topics/Topic/Topic';
@ -110,17 +110,17 @@ describe('Details', () => {
}); });
describe('when remove topic modal is open', () => { describe('when remove topic modal is open', () => {
beforeEach(() => { beforeEach(async () => {
renderComponent(); renderComponent();
const openModalButton = screen.getAllByText('Remove Topic')[0]; const openModalButton = screen.getAllByText('Remove Topic')[0];
userEvent.click(openModalButton); await userEvent.click(openModalButton);
}); });
it('calls deleteTopic on confirm', async () => { it('calls deleteTopic on confirm', async () => {
const submitButton = screen.getAllByRole('button', { const submitButton = screen.getAllByRole('button', {
name: 'Confirm', name: 'Confirm',
})[0]; })[0];
await act(() => userEvent.click(submitButton)); await userEvent.click(submitButton);
expect(mockDelete).toHaveBeenCalledWith(topic.name); expect(mockDelete).toHaveBeenCalledWith(topic.name);
}); });
it('closes the modal when cancel button is clicked', async () => { it('closes the modal when cancel button is clicked', async () => {
@ -134,7 +134,7 @@ describe('Details', () => {
beforeEach(async () => { beforeEach(async () => {
await renderComponent(); await renderComponent();
const confirmButton = screen.getAllByText('Clear messages')[0]; const confirmButton = screen.getAllByText('Clear messages')[0];
await act(() => userEvent.click(confirmButton)); await userEvent.click(confirmButton);
}); });
it('it calls clearTopicMessages on confirm', async () => { it('it calls clearTopicMessages on confirm', async () => {
@ -154,10 +154,10 @@ describe('Details', () => {
}); });
describe('when edit settings is clicked', () => { describe('when edit settings is clicked', () => {
it('redirects to the edit page', () => { it('redirects to the edit page', async () => {
renderComponent(); renderComponent();
const button = screen.getAllByText('Edit settings')[0]; const button = screen.getAllByText('Edit settings')[0];
userEvent.click(button); await userEvent.click(button);
expect(mockNavigate).toHaveBeenCalledWith(clusterTopicEditRelativePath); expect(mockNavigate).toHaveBeenCalledWith(clusterTopicEditRelativePath);
}); });
}); });
@ -169,24 +169,24 @@ describe('Details', () => {
const submitDeleteButton = screen.getByRole('button', { const submitDeleteButton = screen.getByRole('button', {
name: 'Confirm', name: 'Confirm',
}); });
await act(() => userEvent.click(submitDeleteButton)); await userEvent.click(submitDeleteButton);
expect(mockNavigate).toHaveBeenCalledWith('../..'); expect(mockNavigate).toHaveBeenCalledWith('../..');
}); });
it('shows a confirmation popup on deleting topic messages', () => { it('shows a confirmation popup on deleting topic messages', async () => {
renderComponent(); renderComponent();
const clearMessagesButton = screen.getAllByText(/Clear messages/i)[0]; const clearMessagesButton = screen.getAllByText(/Clear messages/i)[0];
userEvent.click(clearMessagesButton); await userEvent.click(clearMessagesButton);
expect( expect(
screen.getByText(/Are you sure want to clear topic messages?/i) screen.getByText(/Are you sure want to clear topic messages?/i)
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it('shows a confirmation popup on recreating topic', () => { it('shows a confirmation popup on recreating topic', async () => {
renderComponent(); renderComponent();
const recreateTopicButton = screen.getByText(/Recreate topic/i); const recreateTopicButton = screen.getByText(/Recreate topic/i);
userEvent.click(recreateTopicButton); await userEvent.click(recreateTopicButton);
expect( expect(
screen.getByText(/Are you sure want to recreate topic?/i) screen.getByText(/Are you sure want to recreate topic?/i)
).toBeInTheDocument(); ).toBeInTheDocument();
@ -195,19 +195,19 @@ describe('Details', () => {
it('is calling recreation function after click on Submit button', async () => { it('is calling recreation function after click on Submit button', async () => {
renderComponent(); renderComponent();
const recreateTopicButton = screen.getByText(/Recreate topic/i); const recreateTopicButton = screen.getByText(/Recreate topic/i);
userEvent.click(recreateTopicButton); await userEvent.click(recreateTopicButton);
const confirmBtn = screen.getByRole('button', { name: /Confirm/i }); const confirmBtn = screen.getByRole('button', { name: /Confirm/i });
await waitFor(() => userEvent.click(confirmBtn)); await waitFor(() => userEvent.click(confirmBtn));
expect(mockRecreate).toBeCalledTimes(1); expect(mockRecreate).toBeCalledTimes(1);
}); });
it('closes popup confirmation window after click on Cancel button', () => { it('closes popup confirmation window after click on Cancel button', async () => {
renderComponent(); renderComponent();
const recreateTopicButton = screen.getByText(/Recreate topic/i); const recreateTopicButton = screen.getByText(/Recreate topic/i);
userEvent.click(recreateTopicButton); await userEvent.click(recreateTopicButton);
const cancelBtn = screen.getByRole('button', { name: /cancel/i }); const cancelBtn = screen.getByRole('button', { name: /cancel/i });
userEvent.click(cancelBtn); await userEvent.click(cancelBtn);
expect( expect(
screen.queryByText(/Are you sure want to recreate topic?/i) screen.queryByText(/Are you sure want to recreate topic?/i)
).not.toBeInTheDocument(); ).not.toBeInTheDocument();

View file

@ -57,7 +57,7 @@ describe('CustomParamsField', () => {
}); });
describe('core functionality works', () => { describe('core functionality works', () => {
it('click on button triggers remove', () => { it('click on button triggers remove', async () => {
setupComponent({ setupComponent({
field, field,
isDisabled, isDisabled,
@ -66,11 +66,11 @@ describe('CustomParamsField', () => {
existingFields, existingFields,
setExistingFields, setExistingFields,
}); });
userEvent.click(screen.getByRole('button')); await userEvent.click(screen.getByRole('button'));
expect(remove).toHaveBeenCalledTimes(1); expect(remove).toHaveBeenCalledTimes(1);
}); });
it('pressing space on button triggers remove', () => { it('pressing space on button triggers remove', async () => {
setupComponent({ setupComponent({
field, field,
isDisabled, isDisabled,
@ -79,7 +79,7 @@ describe('CustomParamsField', () => {
existingFields, existingFields,
setExistingFields, setExistingFields,
}); });
userEvent.type(screen.getByRole('button'), SPACE_KEY); await userEvent.type(screen.getByRole('button'), SPACE_KEY);
// userEvent.type triggers remove two times as at first it clicks on element and then presses space // userEvent.type triggers remove two times as at first it clicks on element and then presses space
expect(remove).toHaveBeenCalledTimes(2); expect(remove).toHaveBeenCalledTimes(2);
}); });

View file

@ -11,10 +11,10 @@ import { TOPIC_CUSTOM_PARAMS } from 'lib/constants';
import { defaultValues } from './fixtures'; import { defaultValues } from './fixtures';
const selectOption = async (listbox: HTMLElement, option: string) => { const selectOption = async (listbox: HTMLElement, option: string) => {
await act(() => { await act(async () => {
userEvent.click(listbox); await userEvent.click(listbox);
}); });
userEvent.click(screen.getByText(option)); await userEvent.click(screen.getByText(option));
}; };
const expectOptionIsSelected = (listbox: HTMLElement, option: string) => { const expectOptionIsSelected = (listbox: HTMLElement, option: string) => {
@ -28,7 +28,9 @@ const expectOptionAvailability = async (
option: string, option: string,
disabled: boolean disabled: boolean
) => { ) => {
await act(() => userEvent.click(listbox)); await act(async () => {
await userEvent.click(listbox);
});
const selectedOptions = within(listbox).getAllByText(option).reverse(); const selectedOptions = within(listbox).getAllByText(option).reverse();
// its either two or one nodes, we only need last one // its either two or one nodes, we only need last one
const selectedOption = selectedOptions[0]; const selectedOption = selectedOptions[0];
@ -43,7 +45,9 @@ const expectOptionAvailability = async (
'cursor', 'cursor',
disabled ? 'not-allowed' : 'pointer' disabled ? 'not-allowed' : 'pointer'
); );
await act(() => userEvent.click(listbox)); await act(async () => {
await userEvent.click(listbox);
});
}; };
const renderComponent = (props: CustomParamsProps, defaults = {}) => { const renderComponent = (props: CustomParamsProps, defaults = {}) => {
@ -85,7 +89,9 @@ describe('CustomParams', () => {
beforeEach(async () => { beforeEach(async () => {
renderComponent({ isSubmitting: false }); renderComponent({ isSubmitting: false });
button = screen.getByRole('button'); button = screen.getByRole('button');
await act(() => userEvent.click(button)); await act(async () => {
await userEvent.click(button);
});
}); });
it('button click creates custom param fieldset', async () => { it('button click creates custom param fieldset', async () => {
@ -120,8 +126,12 @@ describe('CustomParams', () => {
}); });
it('multiple button clicks create multiple fieldsets', async () => { it('multiple button clicks create multiple fieldsets', async () => {
await act(() => userEvent.click(button)); await act(async () => {
await act(() => userEvent.click(button)); await userEvent.click(button);
});
await act(async () => {
await userEvent.click(button);
});
const listboxes = screen.getAllByRole('listbox'); const listboxes = screen.getAllByRole('listbox');
expect(listboxes.length).toBe(3); expect(listboxes.length).toBe(3);
@ -131,7 +141,9 @@ describe('CustomParams', () => {
}); });
it("can't select already selected option", async () => { it("can't select already selected option", async () => {
await act(() => userEvent.click(button)); await act(async () => {
await userEvent.click(button);
});
const listboxes = screen.getAllByRole('listbox'); const listboxes = screen.getAllByRole('listbox');
@ -144,8 +156,12 @@ describe('CustomParams', () => {
}); });
it('when fieldset with selected custom property type is deleted disabled options update correctly', async () => { it('when fieldset with selected custom property type is deleted disabled options update correctly', async () => {
await act(() => userEvent.click(button)); await act(async () => {
await act(() => userEvent.click(button)); await userEvent.click(button);
});
await act(async () => {
await userEvent.click(button);
});
const listboxes = screen.getAllByRole('listbox'); const listboxes = screen.getAllByRole('listbox');
@ -172,7 +188,9 @@ describe('CustomParams', () => {
const deleteSecondFieldsetButton = screen.getByTitle( const deleteSecondFieldsetButton = screen.getByTitle(
'Delete customParam field 1' 'Delete customParam field 1'
); );
await act(() => userEvent.click(deleteSecondFieldsetButton)); await act(async () => {
await userEvent.click(deleteSecondFieldsetButton);
});
expect(secondListbox).not.toBeInTheDocument(); expect(secondListbox).not.toBeInTheDocument();
await expectOptionAvailability( await expectOptionAvailability(

View file

@ -46,9 +46,9 @@ describe('TimeToRetainBtn', () => {
); );
expect(buttonElement).toHaveStyle(`border:none`); expect(buttonElement).toHaveStyle(`border:none`);
}); });
it('should test the non active state with click becoming active', () => { it('should test the non active state with click becoming active', async () => {
const buttonElement = screen.getByRole('button'); const buttonElement = screen.getByRole('button');
userEvent.click(buttonElement); await userEvent.click(buttonElement);
expect(buttonElement).toHaveStyle( expect(buttonElement).toHaveStyle(
`background-color:${theme.button.secondary.invertedColors.normal}` `background-color:${theme.button.secondary.invertedColors.normal}`
); );

View file

@ -67,14 +67,17 @@ describe('TopicForm', () => {
onSubmit: onSubmit.mockImplementation((e) => e.preventDefault()), onSubmit: onSubmit.mockImplementation((e) => e.preventDefault()),
}); });
await act(() => { await act(async () => {
userEvent.type(screen.getByPlaceholderText('Topic Name'), 'topicName'); await userEvent.type(
screen.getByPlaceholderText('Topic Name'),
'topicName'
);
}); });
await act(() => { await act(() => {
fireEvent.submit(screen.getByLabelText('topic form')); fireEvent.submit(screen.getByLabelText('topic form'));
}); });
userEvent.click(screen.getByRole('button', { name: 'Create topic' })); await userEvent.click(screen.getByRole('button', { name: 'Create topic' }));
expect(onSubmit).toBeCalledTimes(1); expect(onSubmit).toBeCalledTimes(1);
}); });
}); });

View file

@ -42,7 +42,7 @@ describe('App', () => {
).toBeInTheDocument(); ).toBeInTheDocument();
}); });
it('handle burger click correctly', () => { it('handle burger click correctly', async () => {
const burger = within(screen.getByLabelText('Page Header')).getByRole( const burger = within(screen.getByLabelText('Page Header')).getByRole(
'button', 'button',
burgerButtonOptions burgerButtonOptions
@ -52,7 +52,7 @@ describe('App', () => {
expect(overlay).toBeInTheDocument(); expect(overlay).toBeInTheDocument();
expect(overlay).toHaveStyleRule('visibility: hidden'); expect(overlay).toHaveStyleRule('visibility: hidden');
expect(burger).toHaveStyleRule('display: none'); expect(burger).toHaveStyleRule('display: none');
userEvent.click(burger); await userEvent.click(burger);
expect(overlay).toHaveStyleRule('visibility: visible'); expect(overlay).toHaveStyleRule('visibility: visible');
}); });

View file

@ -26,9 +26,9 @@ describe('Alert', () => {
expect(screen.getByRole('contentinfo')).toHaveTextContent(message); expect(screen.getByRole('contentinfo')).toHaveTextContent(message);
expect(getButton()).toBeInTheDocument(); expect(getButton()).toBeInTheDocument();
}); });
it('handles dismiss callback', () => { it('handles dismiss callback', async () => {
setupComponent(); setupComponent();
userEvent.click(getButton()); await userEvent.click(getButton());
expect(dismiss).toHaveBeenCalled(); expect(dismiss).toHaveBeenCalled();
}); });
}); });

View file

@ -25,17 +25,17 @@ describe('Custom Input', () => {
describe('number', () => { describe('number', () => {
const getInput = () => screen.getByRole('spinbutton'); const getInput = () => screen.getByRole('spinbutton');
it('allows user to type only numbers', () => { it('allows user to type only numbers', async () => {
render(setupWrapper({ type: 'number' })); render(setupWrapper({ type: 'number' }));
const input = getInput(); const input = getInput();
userEvent.type(input, 'abc131'); await userEvent.type(input, 'abc131');
expect(input).toHaveValue(131); expect(input).toHaveValue(131);
}); });
it('allows negative values', () => { it('allows negative values', async () => {
render(setupWrapper({ type: 'number' })); render(setupWrapper({ type: 'number' }));
const input = getInput(); const input = getInput();
userEvent.type(input, '-2'); await userEvent.type(input, '-2');
expect(input).toHaveValue(-2); expect(input).toHaveValue(-2);
}); });
}); });

View file

@ -11,7 +11,6 @@ import { screen, waitFor } from '@testing-library/dom';
import { ColumnDef, Row } from '@tanstack/react-table'; import { ColumnDef, Row } from '@tanstack/react-table';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { formatTimestamp } from 'lib/dateTimeHelpers'; import { formatTimestamp } from 'lib/dateTimeHelpers';
import { act } from '@testing-library/react';
import { ConnectorState, ConsumerGroupState } from 'generated-sources'; import { ConnectorState, ConsumerGroupState } from 'generated-sources';
const mockedUsedNavigate = jest.fn(); const mockedUsedNavigate = jest.fn();
@ -155,15 +154,15 @@ describe('Table', () => {
}); });
describe('ExpanderCell', () => { describe('ExpanderCell', () => {
it('renders button', () => { it('renders button', async () => {
renderComponent({ getRowCanExpand: () => true }); renderComponent({ getRowCanExpand: () => true });
const btns = screen.getAllByRole('button', { name: 'Expand row' }); const btns = screen.getAllByRole('button', { name: 'Expand row' });
expect(btns.length).toEqual(data.length); expect(btns.length).toEqual(data.length);
expect(screen.queryByText('I am expanded row')).not.toBeInTheDocument(); expect(screen.queryByText('I am expanded row')).not.toBeInTheDocument();
userEvent.click(btns[2]); await userEvent.click(btns[2]);
expect(screen.getByText('I am expanded row')).toBeInTheDocument(); expect(screen.getByText('I am expanded row')).toBeInTheDocument();
userEvent.click(btns[0]); await userEvent.click(btns[0]);
expect(screen.getAllByText('I am expanded row').length).toEqual(2); expect(screen.getAllByText('I am expanded row').length).toEqual(2);
}); });
@ -213,20 +212,20 @@ describe('Table', () => {
expect(lastBtn).toBeInTheDocument(); expect(lastBtn).toBeInTheDocument();
expect(lastBtn).toBeEnabled(); expect(lastBtn).toBeEnabled();
userEvent.click(nextBtn); await userEvent.click(nextBtn);
expect(screen.getByText('ipsum')).toBeInTheDocument(); expect(screen.getByText('ipsum')).toBeInTheDocument();
expect(prevBtn).toBeEnabled(); expect(prevBtn).toBeEnabled();
expect(firstBtn).toBeEnabled(); expect(firstBtn).toBeEnabled();
userEvent.click(lastBtn); await userEvent.click(lastBtn);
expect(screen.getByText('sit')).toBeInTheDocument(); expect(screen.getByText('sit')).toBeInTheDocument();
expect(lastBtn).toBeDisabled(); expect(lastBtn).toBeDisabled();
expect(nextBtn).toBeDisabled(); expect(nextBtn).toBeDisabled();
userEvent.click(prevBtn); await userEvent.click(prevBtn);
expect(screen.getByText('dolor')).toBeInTheDocument(); expect(screen.getByText('dolor')).toBeInTheDocument();
userEvent.click(firstBtn); await userEvent.click(firstBtn);
expect(screen.getByText('lorem')).toBeInTheDocument(); expect(screen.getByText('lorem')).toBeInTheDocument();
}); });
@ -243,22 +242,22 @@ describe('Table', () => {
expect(goToPage).toBeInTheDocument(); expect(goToPage).toBeInTheDocument();
expect(goToPage).toHaveValue(1); expect(goToPage).toHaveValue(1);
}); });
it('updates page on Go To page change', () => { it('updates page on Go To page change', async () => {
const goToPage = getGoToPageInput(); const goToPage = getGoToPageInput();
userEvent.clear(goToPage); await userEvent.clear(goToPage);
userEvent.type(goToPage, '2'); await userEvent.type(goToPage, '2');
expect(goToPage).toHaveValue(2); expect(goToPage).toHaveValue(2);
expect(screen.getByText('ipsum')).toBeInTheDocument(); expect(screen.getByText('ipsum')).toBeInTheDocument();
}); });
it('does not update page on Go To page change if page is out of range', () => { it('does not update page on Go To page change if page is out of range', async () => {
const goToPage = getGoToPageInput(); const goToPage = getGoToPageInput();
userEvent.type(goToPage, '5'); await userEvent.type(goToPage, '5');
expect(goToPage).toHaveValue(15); expect(goToPage).toHaveValue(15);
expect(screen.getByText('No rows found')).toBeInTheDocument(); expect(screen.getByText('No rows found')).toBeInTheDocument();
}); });
it('does not update page on Go To page change if page is not a number', () => { it('does not update page on Go To page change if page is not a number', async () => {
const goToPage = getGoToPageInput(); const goToPage = getGoToPageInput();
userEvent.type(goToPage, 'abc'); await userEvent.type(goToPage, 'abc');
expect(goToPage).toHaveValue(1); expect(goToPage).toHaveValue(1);
}); });
}); });
@ -266,12 +265,10 @@ describe('Table', () => {
describe('Sorting', () => { describe('Sorting', () => {
it('sort rows', async () => { it('sort rows', async () => {
await act(() => await renderComponent({
renderComponent({ path: '/?sortBy=text&&sortDirection=desc',
path: '/?sortBy=text&&sortDirection=desc', enableSorting: true,
enableSorting: true, });
})
);
expect(screen.getAllByRole('row').length).toEqual(data.length + 1); expect(screen.getAllByRole('row').length).toEqual(data.length + 1);
const th = screen.getByRole('columnheader', { name: 'Text' }); const th = screen.getByRole('columnheader', { name: 'Text' });
expect(th).toBeInTheDocument(); expect(th).toBeInTheDocument();
@ -319,42 +316,42 @@ describe('Table', () => {
expect(checkboxes[4]).toBeDisabled(); expect(checkboxes[4]).toBeDisabled();
}); });
it('renders action bar', () => { it('renders action bar', async () => {
expect(screen.getAllByRole('row').length).toEqual(data.length + 1); expect(screen.getAllByRole('row').length).toEqual(data.length + 1);
expect(screen.queryByText('I am Action Bar')).not.toBeInTheDocument(); expect(screen.queryByText('I am Action Bar')).not.toBeInTheDocument();
const checkboxes = screen.getAllByRole('checkbox'); const checkboxes = screen.getAllByRole('checkbox');
expect(checkboxes.length).toEqual(data.length + 1); expect(checkboxes.length).toEqual(data.length + 1);
userEvent.click(checkboxes[2]); await userEvent.click(checkboxes[2]);
expect(screen.getByText('I am Action Bar')).toBeInTheDocument(); expect(screen.getByText('I am Action Bar')).toBeInTheDocument();
}); });
}); });
describe('Clickable Row', () => { describe('Clickable Row', () => {
const onRowClick = jest.fn(); const onRowClick = jest.fn();
it('handles onRowClick', () => { it('handles onRowClick', async () => {
renderComponent({ onRowClick }); renderComponent({ onRowClick });
const rows = screen.getAllByRole('row'); const rows = screen.getAllByRole('row');
expect(rows.length).toEqual(data.length + 1); expect(rows.length).toEqual(data.length + 1);
userEvent.click(rows[1]); await userEvent.click(rows[1]);
expect(onRowClick).toHaveBeenCalledTimes(1); expect(onRowClick).toHaveBeenCalledTimes(1);
}); });
it('does nothing unless onRowClick is provided', () => { it('does nothing unless onRowClick is provided', async () => {
renderComponent(); renderComponent();
const rows = screen.getAllByRole('row'); const rows = screen.getAllByRole('row');
expect(rows.length).toEqual(data.length + 1); expect(rows.length).toEqual(data.length + 1);
userEvent.click(rows[1]); await userEvent.click(rows[1]);
}); });
it('does not handle onRowClick if enableRowSelection', () => { it('does not handle onRowClick if enableRowSelection', async () => {
renderComponent({ onRowClick, enableRowSelection: true }); renderComponent({ onRowClick, enableRowSelection: true });
const rows = screen.getAllByRole('row'); const rows = screen.getAllByRole('row');
expect(rows.length).toEqual(data.length + 1); expect(rows.length).toEqual(data.length + 1);
userEvent.click(rows[1]); await userEvent.click(rows[1]);
expect(onRowClick).not.toHaveBeenCalled(); expect(onRowClick).not.toHaveBeenCalled();
}); });
it('does not handle onRowClick if expandable rows', () => { it('does not handle onRowClick if expandable rows', async () => {
renderComponent({ onRowClick, getRowCanExpand: () => true }); renderComponent({ onRowClick, getRowCanExpand: () => true });
const rows = screen.getAllByRole('row'); const rows = screen.getAllByRole('row');
expect(rows.length).toEqual(data.length + 1); expect(rows.length).toEqual(data.length + 1);
userEvent.click(rows[1]); await userEvent.click(rows[1]);
expect(onRowClick).not.toHaveBeenCalled(); expect(onRowClick).not.toHaveBeenCalled();
}); });
}); });

View file

@ -24,11 +24,11 @@ describe('Search', () => {
setSearchParamsMock, setSearchParamsMock,
]); ]);
}); });
it('calls handleSearch on input', () => { it('calls handleSearch on input', async () => {
render(<Search placeholder={placeholder} />); render(<Search placeholder={placeholder} />);
const input = screen.getByPlaceholderText(placeholder); const input = screen.getByPlaceholderText(placeholder);
userEvent.click(input); await userEvent.click(input);
userEvent.keyboard('value'); await userEvent.keyboard('value');
expect(setSearchParamsMock).toHaveBeenCalledTimes(5); expect(setSearchParamsMock).toHaveBeenCalledTimes(5);
}); });

View file

@ -36,29 +36,29 @@ describe('Custom Select', () => {
expect(getListbox()).toBeInTheDocument(); expect(getListbox()).toBeInTheDocument();
}); });
it('show select options when select is being clicked', () => { it('show select options when select is being clicked', async () => {
expect(getOption()).toBeInTheDocument(); expect(getOption()).toBeInTheDocument();
userEvent.click(getListbox()); await userEvent.click(getListbox());
expect(screen.getAllByRole('option')).toHaveLength(3); expect(screen.getAllByRole('option')).toHaveLength(3);
}); });
it('checking select option change', () => { it('checking select option change', async () => {
const optionLabel = 'test-label1'; const optionLabel = 'test-label1';
userEvent.click(getListbox()); await userEvent.click(getListbox());
userEvent.selectOptions(getListbox(), [optionLabel]); await userEvent.selectOptions(getListbox(), [optionLabel]);
expect(getOption()).toHaveTextContent(optionLabel); expect(getOption()).toHaveTextContent(optionLabel);
}); });
it('trying to select disabled option does not trigger change', () => { it('trying to select disabled option does not trigger change', async () => {
const normalOptionLabel = 'test-label1'; const normalOptionLabel = 'test-label1';
const disabledOptionLabel = 'test-label2'; const disabledOptionLabel = 'test-label2';
userEvent.click(getListbox()); await userEvent.click(getListbox());
userEvent.selectOptions(getListbox(), [normalOptionLabel]); await userEvent.selectOptions(getListbox(), [normalOptionLabel]);
userEvent.click(getListbox()); await userEvent.click(getListbox());
userEvent.selectOptions(getListbox(), [disabledOptionLabel]); await userEvent.selectOptions(getListbox(), [disabledOptionLabel]);
expect(getOption()).toHaveTextContent(normalOptionLabel); expect(getOption()).toHaveTextContent(normalOptionLabel);
}); });

View file

@ -61,7 +61,7 @@ describe('TableHeaderCell', () => {
expect(title).toHaveStyle(`color: ${theme.table.th.color.active};`); expect(title).toHaveStyle(`color: ${theme.table.th.color.active};`);
expect(title).toHaveStyle('cursor: pointer;'); expect(title).toHaveStyle('cursor: pointer;');
}); });
it('renders click on title triggers handler', () => { it('renders click on title triggers handler', async () => {
setupComponent({ setupComponent({
title: testTitle, title: testTitle,
orderBy: TopicColumnsToSort.NAME, orderBy: TopicColumnsToSort.NAME,
@ -69,11 +69,11 @@ describe('TableHeaderCell', () => {
handleOrderBy, handleOrderBy,
}); });
const title = within(getColumnHeader()).getByRole('button'); const title = within(getColumnHeader()).getByRole('button');
userEvent.click(title); await userEvent.click(title);
expect(handleOrderBy.mock.calls.length).toBe(1); expect(handleOrderBy.mock.calls.length).toBe(1);
}); });
it('renders space on title triggers handler', () => { it('renders space on title triggers handler', async () => {
setupComponent({ setupComponent({
title: testTitle, title: testTitle,
orderBy: TopicColumnsToSort.NAME, orderBy: TopicColumnsToSort.NAME,
@ -81,30 +81,30 @@ describe('TableHeaderCell', () => {
handleOrderBy, handleOrderBy,
}); });
const title = within(getColumnHeader()).getByRole('button'); const title = within(getColumnHeader()).getByRole('button');
userEvent.type(title, SPACE_KEY); await userEvent.type(title, SPACE_KEY);
// userEvent.type clicks and only then presses space // userEvent.type clicks and only then presses space
expect(handleOrderBy.mock.calls.length).toBe(2); expect(handleOrderBy.mock.calls.length).toBe(2);
}); });
it('click on preview triggers handler', () => { it('click on preview triggers handler', async () => {
setupComponent({ setupComponent({
title: testTitle, title: testTitle,
previewText: testPreviewText, previewText: testPreviewText,
onPreview, onPreview,
}); });
const preview = within(getColumnHeader()).getByRole('button'); const preview = within(getColumnHeader()).getByRole('button');
userEvent.click(preview); await userEvent.click(preview);
expect(onPreview.mock.calls.length).toBe(1); expect(onPreview.mock.calls.length).toBe(1);
}); });
it('click on preview triggers handler', () => { it('click on preview triggers handler', async () => {
setupComponent({ setupComponent({
title: testTitle, title: testTitle,
previewText: testPreviewText, previewText: testPreviewText,
onPreview, onPreview,
}); });
const preview = within(getColumnHeader()).getByRole('button'); const preview = within(getColumnHeader()).getByRole('button');
userEvent.type(preview, SPACE_KEY); await userEvent.type(preview, SPACE_KEY);
expect(onPreview.mock.calls.length).toBe(2); expect(onPreview.mock.calls.length).toBe(2);
}); });