diff --git a/src/core/packages/application/browser-internal/integration_tests/application_service.test.tsx b/src/core/packages/application/browser-internal/integration_tests/application_service.test.tsx index edd941eed80bd..d42fbfc3d417c 100644 --- a/src/core/packages/application/browser-internal/integration_tests/application_service.test.tsx +++ b/src/core/packages/application/browser-internal/integration_tests/application_service.test.tsx @@ -351,6 +351,9 @@ describe('ApplicationService', () => { await act(async () => { await navigate('/app/app1'); + }); + + await act(async () => { await navigateToApp('app2'); }); @@ -422,6 +425,9 @@ describe('ApplicationService', () => { await act(async () => { await navigate('/app/app1'); + }); + + await act(async () => { await navigateToApp('app2'); }); diff --git a/src/platform/packages/private/kbn-esql-editor/src/editor_footer/history_starred_queries.test.tsx b/src/platform/packages/private/kbn-esql-editor/src/editor_footer/history_starred_queries.test.tsx index 98c0977437fb1..0ed2df7e94e14 100644 --- a/src/platform/packages/private/kbn-esql-editor/src/editor_footer/history_starred_queries.test.tsx +++ b/src/platform/packages/private/kbn-esql-editor/src/editor_footer/history_starred_queries.test.tsx @@ -18,6 +18,7 @@ import { HistoryAndStarredQueriesTabs, } from './history_starred_queries'; import { of } from 'rxjs'; +import { act } from 'react-dom/test-utils'; jest.mock('../history_local_storage', () => { const module = jest.requireActual('../history_local_storage'); @@ -269,7 +270,9 @@ describe('Starred and History queries components', () => { ); // click the starred queries tab - screen.getByTestId('starred-queries-tab').click(); + act(() => { + screen.getByTestId('starred-queries-tab').click(); + }); expect(screen.getByTestId('ESQLEditor-starredQueries')).toBeInTheDocument(); expect(screen.getByTestId('ESQLEditor-history-starred-queries-helpText')).toHaveTextContent( diff --git a/src/platform/packages/private/kbn-react-mute-legacy-root-warning/index.ts b/src/platform/packages/private/kbn-react-mute-legacy-root-warning/index.ts index d77c6f50568a1..e0ce27a9b66b6 100644 --- a/src/platform/packages/private/kbn-react-mute-legacy-root-warning/index.ts +++ b/src/platform/packages/private/kbn-react-mute-legacy-root-warning/index.ts @@ -8,7 +8,6 @@ */ /* eslint-disable no-console */ -const originalConsoleError = console.error; /** * After we upgrade to React 18, we will see a warning in the console that we are using the legacy ReactDOM.render API. @@ -16,6 +15,7 @@ const originalConsoleError = console.error; * However, it is very noisy and we want to mute it for now. */ export function muteLegacyRootWarning() { + const originalConsoleError = console.error; console.error = (message, ...args) => { if ( typeof message === 'string' && @@ -28,4 +28,9 @@ export function muteLegacyRootWarning() { originalConsoleError.call(console, message, ...args); }; + + /* unmute */ + return () => { + console.error = originalConsoleError; + }; } diff --git a/src/platform/packages/shared/kbn-discover-contextual-components/src/data_types/logs/components/summary_column/summary_column.test.tsx b/src/platform/packages/shared/kbn-discover-contextual-components/src/data_types/logs/components/summary_column/summary_column.test.tsx index cdbc87620eb4f..8f61011d052ff 100644 --- a/src/platform/packages/shared/kbn-discover-contextual-components/src/data_types/logs/components/summary_column/summary_column.test.tsx +++ b/src/platform/packages/shared/kbn-discover-contextual-components/src/data_types/logs/components/summary_column/summary_column.test.tsx @@ -10,6 +10,7 @@ import React from 'react'; import { fieldFormatsMock } from '@kbn/field-formats-plugin/common/mocks'; import { render, screen } from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; import SummaryColumn, { AllSummaryColumnProps, SummaryCellPopover, @@ -151,11 +152,13 @@ describe('SummaryColumn', () => { expect(screen.queryByText('+2')).not.toBeInTheDocument(); }); - it('should display a popover with details and actions upon a badge click', () => { + it('should display a popover with details and actions upon a badge click', async () => { const record = getBaseRecord(); renderSummary(record); // Open badge popover - screen.getByTestId(`dataTableCellActionsPopover_${constants.SERVICE_NAME_FIELD}`).click(); + await userEvent.click( + screen.getByTestId(`dataTableCellActionsPopover_${constants.SERVICE_NAME_FIELD}`) + ); expect(screen.getByTestId('dataTableCellActionPopoverTitle')).toHaveTextContent( 'service.name synth-service-2' diff --git a/src/platform/packages/shared/kbn-field-utils/src/components/field_description/field_description.test.tsx b/src/platform/packages/shared/kbn-field-utils/src/components/field_description/field_description.test.tsx index 2bf885f609c36..07f5e76e396e4 100644 --- a/src/platform/packages/shared/kbn-field-utils/src/components/field_description/field_description.test.tsx +++ b/src/platform/packages/shared/kbn-field-utils/src/components/field_description/field_description.test.tsx @@ -10,6 +10,7 @@ import React from 'react'; import { FieldDescription } from './field_description'; import { render, screen } from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; import { FieldsMetadataPublicStart } from '@kbn/fields-metadata-plugin/public'; import { SHOULD_TRUNCATE_FIELD_DESCRIPTION_LOCALSTORAGE_KEY } from './field_description'; @@ -51,12 +52,16 @@ describe('FieldDescription', () => { const customDescription = 'test this long desc '.repeat(8).trim(); render(); expect(screen.queryByTestId('fieldDescription-bytes')).toHaveTextContent(customDescription); - screen.queryByTestId('toggleFieldDescription-bytes')?.click(); + + await userEvent.click(screen.getByTestId('toggleFieldDescription-bytes')); + expect(screen.queryByTestId('fieldDescription-bytes')).toHaveTextContent( `${customDescription}View less` ); expect(mockSetLocalStorage).toHaveBeenCalledWith(false); - screen.queryByTestId('toggleFieldDescription-bytes')?.click(); + + await userEvent.click(screen.getByTestId('toggleFieldDescription-bytes')); + expect(screen.queryByTestId('fieldDescription-bytes')).toHaveTextContent(customDescription); expect(mockSetLocalStorage).toHaveBeenCalledWith(true); }); diff --git a/src/platform/packages/shared/kbn-test/src/jest/resolver.js b/src/platform/packages/shared/kbn-test/src/jest/resolver.js index 84b7a473cf066..8184c399fc44d 100644 --- a/src/platform/packages/shared/kbn-test/src/jest/resolver.js +++ b/src/platform/packages/shared/kbn-test/src/jest/resolver.js @@ -70,13 +70,6 @@ module.exports = (request, options) => { }); } - // This is a workaround to run tests with React 17 and the latest @testing-library/react - // This will be removed once we upgrade to React 18 and start transitioning to the Concurrent Mode - // Tracking issue to clean this up https://github.com/elastic/kibana/issues/199100 - if (request === 'react-dom/client') { - return Path.resolve(__dirname, 'mocks/react_dom_client_mock.ts'); - } - if (request === `elastic-apm-node`) { return APM_AGENT_MOCK; } diff --git a/src/platform/packages/shared/kbn-test/src/jest/setup/enzyme.js b/src/platform/packages/shared/kbn-test/src/jest/setup/enzyme.js index aa4a629303bfa..9fcd8e6afa412 100644 --- a/src/platform/packages/shared/kbn-test/src/jest/setup/enzyme.js +++ b/src/platform/packages/shared/kbn-test/src/jest/setup/enzyme.js @@ -37,5 +37,15 @@ jest.mock('enzyme', () => { mockEnsureEmotionStyleTag(); return actual.render(node, options); }, + mount: (node, options) => { + // Since we're using React 17 enzyme adapter, we need to mute the warning about using legacy root API + // Otherwise console will be flooded with warnings + const unmute = require('@kbn/react-mute-legacy-root-warning').muteLegacyRootWarning(); + try { + return actual.mount(node, options); + } finally { + unmute(); + } + }, }; }); diff --git a/src/platform/packages/shared/kbn-test/src/jest/setup/react_testing_library.js b/src/platform/packages/shared/kbn-test/src/jest/setup/react_testing_library.js index fd9d755a62490..504138d44d331 100644 --- a/src/platform/packages/shared/kbn-test/src/jest/setup/react_testing_library.js +++ b/src/platform/packages/shared/kbn-test/src/jest/setup/react_testing_library.js @@ -16,48 +16,22 @@ import '@testing-library/jest-dom'; * But since newer versions it has stabilised itself */ import { configure } from '@testing-library/react'; -import { version as REACT_VERSION } from 'react'; -import { muteLegacyRootWarning } from '@kbn/react-mute-legacy-root-warning'; // instead of default 'data-testid', use kibana's 'data-test-subj' configure({ testIdAttribute: 'data-test-subj', asyncUtilTimeout: 4500 }); /* eslint-env jest */ -// This is a workaround to run tests with React 17 and the latest @testing-library/react -// Tracking issue to clean this up https://github.com/elastic/kibana/issues/199100 -jest.mock('@testing-library/react', () => { - const actual = jest.requireActual('@testing-library/react'); - - return { - ...actual, - render: (ui, options) => actual.render(ui, { ...options, legacyRoot: true }), - renderHook: (render, options) => actual.renderHook(render, { ...options, legacyRoot: true }), - }; -}); - const consoleFilters = [ /^The above error occurred in the <.*?> component:/, // error boundary output /^Error: Uncaught .+/, // jsdom output ]; -// This is a workaround to run tests with React 17 and the latest @testing-library/react -// And prevent the act warnings that were supposed to be muted by @testing-library -// The testing library mutes the act warnings in some cases by setting IS_REACT_ACT_ENVIRONMENT which is React@18 feature https://github.com/testing-library/react-testing-library/pull/1137/ -// Using this console override we're muting the act warnings as well -// Tracking issue to clean this up https://github.com/elastic/kibana/issues/199100 -// NOTE: we're not muting all the act warnings but only those that testing-library wanted to mute const originalConsoleError = console.error; console.error = (...args) => { const message = args[0]?.toString(); - if (global.IS_REACT_ACT_ENVIRONMENT === false) { - if (message.includes('Warning: An update to %s inside a test was not wrapped in act')) { - return; - } - } - - // Additionally this is a restoration of the original console.error suppression + // This is a restoration of the original console.error suppression // expected by the usage of renderHook from react-hooks-testing-library // which has been moved into latest react-testing-library but the suppression // of the console.error was not moved with it. @@ -72,13 +46,3 @@ console.error = (...args) => { originalConsoleError(...args); }; - -/** - * After we upgrade to React 18, we will see a warning in the console that we are using the legacy ReactDOM.render API. - * This warning is expected as we are in the process of migrating to the new createRoot API. - * However, it is very noisy and we want to mute it for now. - * Tracking issue to clean this up https://github.com/elastic/kibana/issues/199100 - */ -if (REACT_VERSION.startsWith('18.')) { - muteLegacyRootWarning(); -} diff --git a/src/platform/packages/shared/kbn-unified-data-table/src/components/custom_control_columns/additional_row_control/row_menu_control_column.test.tsx b/src/platform/packages/shared/kbn-unified-data-table/src/components/custom_control_columns/additional_row_control/row_menu_control_column.test.tsx index 1c26689bd974e..8d6020bb58633 100644 --- a/src/platform/packages/shared/kbn-unified-data-table/src/components/custom_control_columns/additional_row_control/row_menu_control_column.test.tsx +++ b/src/platform/packages/shared/kbn-unified-data-table/src/components/custom_control_columns/additional_row_control/row_menu_control_column.test.tsx @@ -14,13 +14,14 @@ import { getRowMenuControlColumn } from './row_menu_control_column'; import { dataTableContextMock } from '../../../../__mocks__/table_context'; import { mockRowAdditionalLeadingControls } from '../../../../__mocks__/external_control_columns'; import { UnifiedDataTableContext } from '../../../table_context'; +import userEvent from '@testing-library/user-event'; describe('getRowMenuControlColumn', () => { const contextMock = { ...dataTableContextMock, }; - it('should render the component', () => { + it('should render the component', async () => { const mockClick = jest.fn(); const props = { id: 'test_row_menu_control', @@ -57,7 +58,7 @@ describe('getRowMenuControlColumn', () => { const menuButton = screen.getByTestId('unifiedDataTable_test_row_menu_control'); expect(menuButton).toBeInTheDocument(); - menuButton.click(); + await userEvent.click(menuButton); expect(screen.getByTestId('exampleRowControl-visBarVerticalStacked')).toBeInTheDocument(); expect(screen.getByTestId('exampleRowControl-heart')).toBeInTheDocument(); @@ -65,7 +66,8 @@ describe('getRowMenuControlColumn', () => { const button = screen.getByTestId('unifiedDataTable_rowMenu_test_row_menu_control'); expect(button).toBeInTheDocument(); - button.click(); + await userEvent.click(button); + expect(mockClick).toHaveBeenCalledWith({ record: contextMock.getRowByIndex(1), rowIndex: 1 }); }); }); diff --git a/src/platform/packages/shared/kbn-unified-data-table/src/components/data_table.test.tsx b/src/platform/packages/shared/kbn-unified-data-table/src/components/data_table.test.tsx index 82577352fb19c..dbc8d61b46f99 100644 --- a/src/platform/packages/shared/kbn-unified-data-table/src/components/data_table.test.tsx +++ b/src/platform/packages/shared/kbn-unified-data-table/src/components/data_table.test.tsx @@ -1555,7 +1555,7 @@ describe('UnifiedDataTable', () => { expect(screen.getByTestId(BUTTON_TEST_SUBJ)).toBeInTheDocument(); - screen.getByTestId(BUTTON_TEST_SUBJ).click(); + await userEvent.click(screen.getByTestId(BUTTON_TEST_SUBJ)); expect(screen.getByTestId(INPUT_TEST_SUBJ)).toBeInTheDocument(); diff --git a/src/platform/packages/shared/kbn-unified-data-table/src/components/data_table_document_selection.test.tsx b/src/platform/packages/shared/kbn-unified-data-table/src/components/data_table_document_selection.test.tsx index 85ce60d78aa16..e9d54e9cbf049 100644 --- a/src/platform/packages/shared/kbn-unified-data-table/src/components/data_table_document_selection.test.tsx +++ b/src/platform/packages/shared/kbn-unified-data-table/src/components/data_table_document_selection.test.tsx @@ -27,6 +27,7 @@ import { getDocId } from '@kbn/discover-utils'; import { render, screen } from '@testing-library/react'; import { __IntlProvider as IntlProvider } from '@kbn/i18n-react'; import { servicesMock } from '../../__mocks__/services'; +import userEvent from '@testing-library/user-event'; describe('document selection', () => { describe('getDocId', () => { @@ -409,7 +410,7 @@ describe('document selection', () => { return { getButton: async () => { const menuButton = await screen.findByTestId('unifiedDataTableSelectionBtn'); - menuButton.click(); + await userEvent.click(menuButton); return screen.queryByRole('button', { name: /Compare/ }); }, }; diff --git a/src/platform/packages/shared/kbn-unified-doc-viewer/src/components/doc_viewer/doc_viewer.test.tsx b/src/platform/packages/shared/kbn-unified-doc-viewer/src/components/doc_viewer/doc_viewer.test.tsx index 81585be17f0ce..f68a84d02a85c 100644 --- a/src/platform/packages/shared/kbn-unified-doc-viewer/src/components/doc_viewer/doc_viewer.test.tsx +++ b/src/platform/packages/shared/kbn-unified-doc-viewer/src/components/doc_viewer/doc_viewer.test.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { mount, shallow } from 'enzyme'; -import { render, screen } from '@testing-library/react'; +import { act, render, screen } from '@testing-library/react'; import { findTestSubject } from '@elastic/eui/lib/test'; import { buildDataTableRecord } from '@kbn/discover-utils'; import { DocViewer, INITIAL_TAB } from './doc_viewer'; @@ -88,13 +88,17 @@ describe('', () => { expect(screen.getByTestId('docViewerTab-test1').getAttribute('aria-selected')).toBe('true'); expect(screen.getByTestId('docViewerTab-test2').getAttribute('aria-selected')).toBe('false'); - screen.getByTestId('docViewerTab-test2').click(); + act(() => { + screen.getByTestId('docViewerTab-test2').click(); + }); expect(screen.getByTestId('docViewerTab-test1').getAttribute('aria-selected')).toBe('false'); expect(screen.getByTestId('docViewerTab-test2').getAttribute('aria-selected')).toBe('true'); expect(mockSetLocalStorage).toHaveBeenCalledWith('kbn_doc_viewer_tab_test2'); - screen.getByTestId('docViewerTab-test1').click(); + act(() => { + screen.getByTestId('docViewerTab-test1').click(); + }); expect(screen.getByTestId('docViewerTab-test1').getAttribute('aria-selected')).toBe('true'); expect(screen.getByTestId('docViewerTab-test2').getAttribute('aria-selected')).toBe('false'); diff --git a/src/platform/packages/shared/kbn-unified-tabs/src/components/tab/tab.test.tsx b/src/platform/packages/shared/kbn-unified-tabs/src/components/tab/tab.test.tsx index 3eb8ee7e454e7..3665966219342 100644 --- a/src/platform/packages/shared/kbn-unified-tabs/src/components/tab/tab.test.tsx +++ b/src/platform/packages/shared/kbn-unified-tabs/src/components/tab/tab.test.tsx @@ -8,7 +8,7 @@ */ import React from 'react'; -import { render, screen, waitFor } from '@testing-library/react'; +import { act, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { Tab } from './tab'; import { MAX_TAB_WIDTH, MIN_TAB_WIDTH } from '../../constants'; @@ -96,7 +96,9 @@ describe('Tab', () => { ); const tabMenuButton = screen.getByTestId(`unifiedTabs_tabMenuBtn_${tabItem.id}`); - tabMenuButton.click(); + act(() => { + tabMenuButton.click(); + }); expect(getTabMenuItems).toHaveBeenCalledWith(tabItem); diff --git a/src/platform/packages/shared/presentation/presentation_publishing/publishing_subject/publishing_subject.test.tsx b/src/platform/packages/shared/presentation/presentation_publishing/publishing_subject/publishing_subject.test.tsx index 1aca29fc10fae..a48230a56f239 100644 --- a/src/platform/packages/shared/presentation/presentation_publishing/publishing_subject/publishing_subject.test.tsx +++ b/src/platform/packages/shared/presentation/presentation_publishing/publishing_subject/publishing_subject.test.tsx @@ -256,7 +256,7 @@ describe('publishing subject', () => { screen.getByText('value1: 1, value2: 1, value3: 1, value4: 1, value5: 1, value6: 1') ).toBeInTheDocument(); }); - expect(renderCount).toBe(7); + expect(renderCount).toBe(2); }); }); diff --git a/src/platform/packages/shared/response-ops/alerts-fields-browser/components/categories_selector/categories_selector.test.tsx b/src/platform/packages/shared/response-ops/alerts-fields-browser/components/categories_selector/categories_selector.test.tsx index 6ef4139ca787d..1bf4c4629a36e 100644 --- a/src/platform/packages/shared/response-ops/alerts-fields-browser/components/categories_selector/categories_selector.test.tsx +++ b/src/platform/packages/shared/response-ops/alerts-fields-browser/components/categories_selector/categories_selector.test.tsx @@ -12,6 +12,7 @@ import { render } from '@testing-library/react'; import { waitForEuiPopoverOpen } from '@elastic/eui/lib/test/rtl'; import { mockBrowserFields } from '../../mock'; import { CategoriesSelector } from './categories_selector'; +import userEvent from '@testing-library/user-event'; const mockSetSelectedCategoryIds = jest.fn(); const defaultProps = { @@ -70,10 +71,10 @@ describe('CategoriesSelector', () => { it('should call setSelectedCategoryIds when category selected', async () => { const result = render(); - result.getByTestId('categories-filter-button').click(); + await userEvent.click(result.getByTestId('categories-filter-button')); await waitForEuiPopoverOpen(); - result.getByTestId(`categories-selector-option-base`).click(); + await userEvent.click(result.getByTestId(`categories-selector-option-base`)); expect(mockSetSelectedCategoryIds).toHaveBeenCalledWith(['base']); }); }); diff --git a/src/platform/packages/shared/response-ops/alerts-fields-browser/components/field_table/field_table.test.tsx b/src/platform/packages/shared/response-ops/alerts-fields-browser/components/field_table/field_table.test.tsx index 5d85abbd6295a..a58856f205198 100644 --- a/src/platform/packages/shared/response-ops/alerts-fields-browser/components/field_table/field_table.test.tsx +++ b/src/platform/packages/shared/response-ops/alerts-fields-browser/components/field_table/field_table.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { render, RenderResult } from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; import { mockBrowserFields } from '../../mock'; import { FieldTable, FieldTableProps } from './field_table'; @@ -142,42 +143,42 @@ describe('FieldTable', () => { const isAtFirstPage = (result: RenderResult) => result.getByTestId('pagination-button-0').hasAttribute('aria-current'); - const changePage = (result: RenderResult) => { - result.getByTestId('pagination-button-1').click(); + const changePage = async (result: RenderResult) => { + await userEvent.click(result.getByTestId('pagination-button-1')); }; const paginationProps = { filteredBrowserFields: mockBrowserFields, }; - it('should paginate on page clicked', () => { + it('should paginate on page clicked', async () => { const result = renderComponent(paginationProps); expect(isAtFirstPage(result)).toBeTruthy(); - changePage(result); + await changePage(result); expect(isAtFirstPage(result)).toBeFalsy(); }); - it('should not reset on field checked', () => { + it('should not reset on field checked', async () => { const result = renderComponent(paginationProps); - changePage(result); + await changePage(result); - result.getAllByRole('checkbox').at(0)?.click(); + await userEvent.click(result.getAllByRole('checkbox').at(0)!); expect(mockOnToggleColumn).toHaveBeenCalled(); // assert some field has been selected expect(isAtFirstPage(result)).toBeFalsy(); }); - it('should reset on filter change', () => { + it('should reset on filter change', async () => { const result = renderComponent({ ...paginationProps, selectedCategoryIds: ['destination', 'event', 'client', 'agent', 'host'], }); - changePage(result); + await changePage(result); expect(isAtFirstPage(result)).toBeFalsy(); result.rerender( diff --git a/src/platform/packages/shared/response-ops/alerts-table/reducers/bulk_actions_reducer.test.tsx b/src/platform/packages/shared/response-ops/alerts-table/reducers/bulk_actions_reducer.test.tsx index 48bbd6de8f584..62f7358969f55 100644 --- a/src/platform/packages/shared/response-ops/alerts-table/reducers/bulk_actions_reducer.test.tsx +++ b/src/platform/packages/shared/response-ops/alerts-table/reducers/bulk_actions_reducer.test.tsx @@ -617,7 +617,9 @@ describe('AlertsDataGrid bulk actions', () => { await userEvent.click(await screen.findByText('Fake Bulk Action')); // the callback given to our clients to run when they want to update the loading state - mockOnClick.mock.calls[0][2](false); + act(() => { + mockOnClick.mock.calls[0][2](false); + }); expect(screen.queryByTestId('row-loader')).not.toBeInTheDocument(); }); diff --git a/src/platform/packages/shared/shared-ux/chrome/navigation/__jest__/panel.test.tsx b/src/platform/packages/shared/shared-ux/chrome/navigation/__jest__/panel.test.tsx index 0a0a29edc9f8f..f38f973529439 100644 --- a/src/platform/packages/shared/shared-ux/chrome/navigation/__jest__/panel.test.tsx +++ b/src/platform/packages/shared/shared-ux/chrome/navigation/__jest__/panel.test.tsx @@ -16,6 +16,7 @@ import { of } from 'rxjs'; import type { NavigationTreeDefinitionUI } from '@kbn/core-chrome-browser'; import { renderNavigation } from './utils'; +import { act } from '@testing-library/react'; describe('Panel', () => { test('should render group as panel opener', async () => { @@ -54,7 +55,10 @@ describe('Panel', () => { expect(await findByTestId(/nav-item-root.group1/)).toBeVisible(); expect(queryByTestId(/sideNavPanel/)).toBeNull(); - (await findByTestId(/nav-item-root.group1/)).click(); // open the panel + await act(async () => { + (await findByTestId(/nav-item-root.group1/)).click(); // open the panel + }); + expect(queryByTestId(/sideNavPanel/)).toBeVisible(); }); @@ -142,7 +146,9 @@ describe('Panel', () => { }); // open the panel - (await findByTestId(/nav-item-id-group1/)).click(); + await act(async () => { + (await findByTestId(/nav-item-id-group1/)).click(); + }); expect(queryByTestId(/sideNavPanel/)).toBeVisible(); // close the panel @@ -156,7 +162,9 @@ describe('Panel', () => { }); // open the panel via the button - (await findByTestId(/nav-item-id-group1/)).click(); + await act(async () => { + (await findByTestId(/nav-item-id-group1/)).click(); + }); expect(queryByTestId(/sideNavPanel/)).toBeVisible(); // click the label element @@ -173,7 +181,9 @@ describe('Panel', () => { }); // open the panel via the button - (await findByTestId(/nav-item-id-group1/)).click(); + await act(async () => { + (await findByTestId(/nav-item-id-group1/)).click(); + }); expect(queryByTestId(/sideNavPanel/)).toBeVisible(); // click the label element @@ -190,7 +200,9 @@ describe('Panel', () => { }); // open the panel via the button - (await findByTestId(/nav-item-id-group1/)).click(); + await act(async () => { + (await findByTestId(/nav-item-id-group1/)).click(); + }); expect(queryByTestId(/sideNavPanel/)).toBeVisible(); // click an element outside of the panel @@ -260,7 +272,9 @@ describe('Panel', () => { navTreeDef: of(navTree), }); - queryByTestId(/nav-item-root.group1/)?.click(); // open the panel + act(() => { + queryByTestId(/nav-item-root.group1/)?.click(); // open the panel + }); expect(queryByTestId(/panelGroupId-foo/)).toBeVisible(); expect(queryByTestId(/panelGroupTitleId-foo/)?.textContent).toBe('Foo'); @@ -327,7 +341,9 @@ describe('Panel', () => { navTreeDef: of(navTree), }); - queryByTestId(/nav-item-root.group1/)?.click(); // open the panel + act(() => { + queryByTestId(/nav-item-root.group1/)?.click(); // open the panel + }); expect(queryByTestId(/panelGroupTitleId-foo/)).toBeNull(); // No title rendered @@ -394,7 +410,9 @@ describe('Panel', () => { navTreeDef: of(navTree), }); - queryByTestId(/nav-item-root.group1/)?.click(); // open the panel + act(() => { + queryByTestId(/nav-item-root.group1/)?.click(); // open the panel + }); expect(queryByTestId(/panelGroupId-foo/)).toBeVisible(); @@ -404,7 +422,9 @@ describe('Panel', () => { expect(queryByTestId(/panelNavItem-id-item1/)).not.toBeVisible(); // Accordion is collapsed expect(queryByTestId(/panelNavItem-id-item3/)).not.toBeVisible(); // Accordion is collapsed - queryByTestId(/panelAccordionBtnId-foo/)?.click(); // Expand accordion + act(() => { + queryByTestId(/panelAccordionBtnId-foo/)?.click(); // Expand accordion + }); expect(queryByTestId(/panelNavItem-id-item1/)).toBeVisible(); expect(queryByTestId(/panelNavItem-id-item3/)).toBeVisible(); @@ -463,7 +483,9 @@ describe('Panel', () => { navTreeDef: of(navTree), }); - queryByTestId(/nav-item-root.group1/)?.click(); // open the panel + act(() => { + queryByTestId(/nav-item-root.group1/)?.click(); // open the panel + }); expect(queryByTestId(/panelGroupId-foo/)).toBeVisible(); // no crash }); @@ -520,7 +542,9 @@ describe('Panel', () => { expect(componentSpy).not.toHaveBeenCalled(); - queryByTestId(/nav-item-root.group1/)?.click(); // open the panel + act(() => { + queryByTestId(/nav-item-root.group1/)?.click(); // open the panel + }); expect(componentSpy).toHaveBeenCalled(); }); diff --git a/src/platform/packages/shared/shared-ux/error_boundary/src/services/error_boundary_services.test.tsx b/src/platform/packages/shared/shared-ux/error_boundary/src/services/error_boundary_services.test.tsx index dd7589fb83738..65d9fb02453b1 100644 --- a/src/platform/packages/shared/shared-ux/error_boundary/src/services/error_boundary_services.test.tsx +++ b/src/platform/packages/shared/shared-ux/error_boundary/src/services/error_boundary_services.test.tsx @@ -14,6 +14,7 @@ import { analyticsServiceMock } from '@kbn/core-analytics-browser-mocks'; import { KibanaErrorBoundaryProviderDeps } from '../../types'; import { KibanaErrorBoundary, KibanaErrorBoundaryProvider } from '../..'; import { BadComponent } from '../../mocks'; +import userEvent from '@testing-library/user-event'; describe('', () => { let analytics: KibanaErrorBoundaryProviderDeps['analytics']; @@ -32,7 +33,7 @@ describe('', () => { ); - (await findByTestId('clickForErrorBtn')).click(); + await userEvent.click(await findByTestId('clickForErrorBtn')); expect(reportEventSpy).toBeCalledWith('fatal-error-react', { component_name: 'BadComponent', @@ -60,7 +61,7 @@ describe('', () => { ); - (await findByTestId('clickForErrorBtn')).click(); + await userEvent.click(await findByTestId('clickForErrorBtn')); expect(reportEventSpy2).not.toBeCalled(); expect(reportEventSpy1).toBeCalledWith('fatal-error-react', { diff --git a/src/platform/packages/shared/shared-ux/error_boundary/src/ui/error_boundary.test.tsx b/src/platform/packages/shared/shared-ux/error_boundary/src/ui/error_boundary.test.tsx index 5cffd20950e8f..9df44da1a587e 100644 --- a/src/platform/packages/shared/shared-ux/error_boundary/src/ui/error_boundary.test.tsx +++ b/src/platform/packages/shared/shared-ux/error_boundary/src/ui/error_boundary.test.tsx @@ -8,6 +8,7 @@ */ import { render } from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; import React, { FC, PropsWithChildren } from 'react'; import { apm } from '@elastic/apm-rum'; @@ -50,12 +51,12 @@ describe('', () => { ); - (await findByTestId('clickForErrorBtn')).click(); + await userEvent.click(await findByTestId('clickForErrorBtn')); expect(await findByText(strings.page.callout.recoverable.title())).toBeVisible(); expect(await findByText(strings.page.callout.recoverable.pageReloadButton())).toBeVisible(); - (await findByTestId('errorBoundaryRecoverablePromptReloadBtn')).click(); + await userEvent.click(await findByTestId('errorBoundaryRecoverablePromptReloadBtn')); expect(reloadSpy).toHaveBeenCalledTimes(1); }); @@ -68,14 +69,14 @@ describe('', () => { ); - (await findByTestId('clickForErrorBtn')).click(); + await userEvent.click(await findByTestId('clickForErrorBtn')); expect(await findByText(strings.page.callout.fatal.title())).toBeVisible(); expect(await findByText(strings.page.callout.fatal.body())).toBeVisible(); expect(await findByText(strings.page.callout.fatal.showDetailsButton())).toBeVisible(); expect(await findByText(strings.page.callout.fatal.pageReloadButton())).toBeVisible(); - (await findByTestId('errorBoundaryFatalPromptReloadBtn')).click(); + await userEvent.click(await findByTestId('errorBoundaryFatalPromptReloadBtn')); expect(reloadSpy).toHaveBeenCalledTimes(1); }); @@ -91,7 +92,7 @@ describe('', () => { ); - (await findByTestId('clickForErrorBtn')).click(); + await userEvent.click(await findByTestId('clickForErrorBtn')); expect(mockDeps.analytics.reportEvent.mock.calls[0][0]).toBe('fatal-error-react'); expect(mockDeps.analytics.reportEvent.mock.calls[0][1]).toMatchObject({ @@ -111,7 +112,7 @@ describe('', () => { ); - (await findByTestId('clickForErrorBtn')).click(); + await userEvent.click(await findByTestId('clickForErrorBtn')); expect( mockDeps.analytics.reportEvent.mock.calls[0][1].component_stack.includes('at BadComponent') @@ -129,7 +130,7 @@ describe('', () => { ); - (await findByTestId('clickForErrorBtn')).click(); + await userEvent.click(await findByTestId('clickForErrorBtn')); expect(apm.captureError).toHaveBeenCalledTimes(1); expect(apm.captureError).toHaveBeenCalledWith( diff --git a/src/platform/packages/shared/shared-ux/error_boundary/src/ui/section_error_boundary.test.tsx b/src/platform/packages/shared/shared-ux/error_boundary/src/ui/section_error_boundary.test.tsx index 5aed2ef73f317..289e4bf7afed4 100644 --- a/src/platform/packages/shared/shared-ux/error_boundary/src/ui/section_error_boundary.test.tsx +++ b/src/platform/packages/shared/shared-ux/error_boundary/src/ui/section_error_boundary.test.tsx @@ -8,6 +8,7 @@ */ import { render } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import React, { FC, PropsWithChildren } from 'react'; import { apm } from '@elastic/apm-rum'; @@ -44,7 +45,7 @@ describe('', () => { expect(res.getByText(inputText)).toBeInTheDocument(); }); - it('renders a recoverable prompt when a recoverable error is caught', () => { + it('renders a recoverable prompt when a recoverable error is caught', async () => { const reloadSpy = jest.spyOn(services, 'onClickRefresh'); const { getByTestId, getByText } = render( @@ -52,24 +53,24 @@ describe('', () => { ); - getByTestId('clickForErrorBtn').click(); + await userEvent.click(getByTestId('clickForErrorBtn')); expect(getByText(strings.section.callout.recoverable.title('test section name'))).toBeVisible(); expect(getByText(strings.section.callout.recoverable.body('test section name'))).toBeVisible(); expect(getByText(strings.section.callout.recoverable.pageReloadButton())).toBeVisible(); - getByTestId('sectionErrorBoundaryRecoverBtn').click(); + await userEvent.click(getByTestId('sectionErrorBoundaryRecoverBtn')); expect(reloadSpy).toHaveBeenCalledTimes(1); }); - it('renders a fatal prompt when a fatal error is caught', () => { + it('renders a fatal prompt when a fatal error is caught', async () => { const { getByTestId, getByText } = render( ); - getByTestId('clickForErrorBtn').click(); + await userEvent.click(getByTestId('clickForErrorBtn')); expect(getByText(strings.section.callout.fatal.title('test section name'))).toBeVisible(); expect(getByText(strings.section.callout.fatal.body('test section name'))).toBeVisible(); @@ -87,7 +88,7 @@ describe('', () => { ); - (await findByTestId('clickForErrorBtn')).click(); + await userEvent.click(await findByTestId('clickForErrorBtn')); expect(mockDeps.analytics.reportEvent.mock.calls[0][0]).toBe('fatal-error-react'); expect(mockDeps.analytics.reportEvent.mock.calls[0][1]).toMatchObject({ @@ -107,7 +108,7 @@ describe('', () => { ); - (await findByTestId('clickForErrorBtn')).click(); + await userEvent.click(await findByTestId('clickForErrorBtn')); expect( mockDeps.analytics.reportEvent.mock.calls[0][1].component_stack.includes('at BadComponent') @@ -125,7 +126,7 @@ describe('', () => { ); - (await findByTestId('clickForErrorBtn')).click(); + await userEvent.click(await findByTestId('clickForErrorBtn')); expect(apm.captureError).toHaveBeenCalledTimes(1); expect(apm.captureError).toHaveBeenCalledWith( diff --git a/src/platform/plugins/shared/discover/public/embeddable/get_search_embeddable_factory.test.tsx b/src/platform/plugins/shared/discover/public/embeddable/get_search_embeddable_factory.test.tsx index 3ef59ad7a252b..eccad7ba927a8 100644 --- a/src/platform/plugins/shared/discover/public/embeddable/get_search_embeddable_factory.test.tsx +++ b/src/platform/plugins/shared/discover/public/embeddable/get_search_embeddable_factory.test.tsx @@ -135,12 +135,12 @@ describe('saved search embeddable', () => { await waitOneTick(); expect(api.dataLoading$.getValue()).toBe(false); - expect(discoverComponent.queryByTestId('embeddedSavedSearchDocTable')).toBeInTheDocument(); - await waitFor(() => + await waitFor(() => { + expect(discoverComponent.queryByTestId('embeddedSavedSearchDocTable')).toBeInTheDocument(); expect(discoverComponent.getByTestId('embeddedSavedSearchDocTable').textContent).toEqual( 'No results found' - ) - ); + ); + }); }); it('should render field stats table in AGGREGATED_LEVEL view mode', async () => { @@ -303,9 +303,11 @@ describe('saved search embeddable', () => { await waitOneTick(); expect(api.dataLoading$.getValue()).toBe(false); - const discoverGridComponent = discoverComponent.queryByTestId('discoverDocTable'); - expect(discoverGridComponent).toBeInTheDocument(); - expect(discoverComponent.queryByText('data-source-profile')).toBeInTheDocument(); + await waitFor(() => { + const discoverGridComponent = discoverComponent.queryByTestId('discoverDocTable'); + expect(discoverGridComponent).toBeInTheDocument(); + expect(discoverComponent.queryByText('data-source-profile')).toBeInTheDocument(); + }); }); }); }); diff --git a/src/platform/plugins/shared/esql/public/triggers/esql_controls/control_flyout/choose_column_popover.test.tsx b/src/platform/plugins/shared/esql/public/triggers/esql_controls/control_flyout/choose_column_popover.test.tsx index 0a1a997a36179..b0940aaca7df1 100644 --- a/src/platform/plugins/shared/esql/public/triggers/esql_controls/control_flyout/choose_column_popover.test.tsx +++ b/src/platform/plugins/shared/esql/public/triggers/esql_controls/control_flyout/choose_column_popover.test.tsx @@ -9,22 +9,25 @@ import React from 'react'; import { render, screen, fireEvent } from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; import { ChooseColumnPopover } from './choose_column_popover'; describe('ChooseColumnPopover', () => { - it('should render a search input and a list', () => { + it('should render a search input and a list', async () => { + const user = userEvent.setup(); render(); // open the popover - screen.getByTestId('chooseColumnBtn').click(); + await user.click(screen.getByTestId('chooseColumnBtn')); // expect the search input to be rendered expect(screen.getByTestId('selectableColumnSearch')).toBeInTheDocument(); expect(screen.getByTestId('selectableColumnList')).toBeInTheDocument(); }); - it('should update the list when there is a text in the input', () => { + it('should update the list when there is a text in the input', async () => { + const user = userEvent.setup(); render(); // open the popover - screen.getByTestId('chooseColumnBtn').click(); + await user.click(screen.getByTestId('chooseColumnBtn')); // expect the search input to be rendered // type in the search input @@ -37,11 +40,12 @@ describe('ChooseColumnPopover', () => { expect(listItems).toHaveTextContent('col2'); }); - it('should call the updateQuery prop if a list item is clicked', () => { + it('should call the updateQuery prop if a list item is clicked', async () => { + const user = userEvent.setup(); const updateQuerySpy = jest.fn(); render(); // open the popover - screen.getByTestId('chooseColumnBtn').click(); + await user.click(screen.getByTestId('chooseColumnBtn')); // expect the search input to be rendered // type in the search input @@ -52,7 +56,7 @@ describe('ChooseColumnPopover', () => { const listItems = list.querySelector('li'); // click the list item - if (listItems) fireEvent.click(listItems); + if (listItems) await user.click(listItems); expect(updateQuerySpy).toHaveBeenCalledWith('col2'); }); }); diff --git a/src/platform/plugins/shared/home/public/application/components/tutorial/tutorial.test.tsx b/src/platform/plugins/shared/home/public/application/components/tutorial/tutorial.test.tsx index 6e7c877fb2b4c..958097e7b4975 100644 --- a/src/platform/plugins/shared/home/public/application/components/tutorial/tutorial.test.tsx +++ b/src/platform/plugins/shared/home/public/application/components/tutorial/tutorial.test.tsx @@ -9,7 +9,7 @@ import React from 'react'; import { I18nProvider } from '@kbn/i18n-react'; -import { fireEvent, render, waitFor } from '@testing-library/react'; +import { act, fireEvent, render, waitFor } from '@testing-library/react'; import { Tutorial } from './tutorial'; import { TutorialType } from '../../../services/tutorials/types'; @@ -97,7 +97,10 @@ describe('Tutorial component', () => { /> ); - await loadTutorialPromise; + + await act(async () => { + await loadTutorialPromise; + }); expect(getByText('onPrem instructions')).toBeInTheDocument(); }); @@ -123,7 +126,9 @@ describe('Tutorial component', () => { /> ); - await loadBasicTutorialPromise; + await act(async () => { + await loadBasicTutorialPromise; + }); expect(queryByTestId('selfManagedTutorial')).not.toBeInTheDocument(); expect(queryByTestId('onCloudTutorial')).not.toBeInTheDocument(); @@ -141,7 +146,10 @@ describe('Tutorial component', () => { /> ); - await loadTutorialPromise; + await act(async () => { + await loadTutorialPromise; + }); + fireEvent.click(getByTestId('onCloudTutorial')); await waitFor(() => { @@ -163,7 +171,9 @@ describe('Tutorial component', () => { /> ); - await loadTutorialPromise; + await act(async () => { + await loadTutorialPromise; + }); expect(getByText('elasticCloud instructions')).toBeInTheDocument(); }); @@ -182,7 +192,10 @@ describe('Tutorial component', () => { /> ); - await loadTutorialPromise; + + await act(async () => { + await loadTutorialPromise; + }); // Simulate status check fireEvent.click(getByTestId('statusCheckButton')); @@ -212,7 +225,9 @@ describe('Tutorial component', () => { /> ); - await loadTutorialWithNoDataCheckPromise; + await act(async () => { + await loadTutorialWithNoDataCheckPromise; + }); // Simulate status check fireEvent.click(getByTestId('statusCheckButton')); diff --git a/src/platform/plugins/shared/unified_doc_viewer/public/components/doc_viewer_table/table_cell_value.test.tsx b/src/platform/plugins/shared/unified_doc_viewer/public/components/doc_viewer_table/table_cell_value.test.tsx index d9470a7290647..744be2168160c 100644 --- a/src/platform/plugins/shared/unified_doc_viewer/public/components/doc_viewer_table/table_cell_value.test.tsx +++ b/src/platform/plugins/shared/unified_doc_viewer/public/components/doc_viewer_table/table_cell_value.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { render, screen } from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; import { TableFieldValue } from './table_cell_value'; import { setUnifiedDocViewerServices } from '../../plugin'; import { mockUnifiedDocViewerServices } from '../../__mocks__'; @@ -64,7 +65,7 @@ describe('TableFieldValue', () => { expect(valueElement.getAttribute('css')).toBeDefined(); expect(valueElement.classList.contains('kbnDocViewer__value--truncated')).toBe(true); - toggleButton.click(); + await userEvent.click(toggleButton); toggleButton = screen.getByTestId('toggleLongFieldValue-message'); expect(toggleButton).toBeInTheDocument(); @@ -74,7 +75,7 @@ describe('TableFieldValue', () => { expect(valueElement.getAttribute('css')).toBeNull(); expect(valueElement.classList.contains('kbnDocViewer__value--truncated')).toBe(false); - toggleButton.click(); + await userEvent.click(toggleButton); toggleButton = screen.getByTestId('toggleLongFieldValue-message'); expect(toggleButton).toBeInTheDocument(); diff --git a/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/api/chat_complete/use_chat_complete.test.ts b/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/api/chat_complete/use_chat_complete.test.ts index 48d00163f66d3..3ed022410c327 100644 --- a/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/api/chat_complete/use_chat_complete.test.ts +++ b/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/api/chat_complete/use_chat_complete.test.ts @@ -86,7 +86,10 @@ describe('useChatComplete', () => { it('should set isLoading to true while sending a message and false after completion', async () => { (postChatComplete as jest.Mock).mockResolvedValue({}); - const { result } = renderHook(() => useChatComplete({ connectorId: 'mock-connector-id' })); + const { result } = renderHook(() => useChatComplete({ connectorId: 'mock-connector-id' }), { + // TODO: fails with concurrent mode + legacyRoot: true, + }); expect(result.current.isLoading).toBe(false); diff --git a/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/api/conversations/conversations.test.tsx b/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/api/conversations/conversations.test.tsx index 50ae344a78671..f63d40f6fe9e3 100644 --- a/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/api/conversations/conversations.test.tsx +++ b/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/api/conversations/conversations.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { act, waitFor, renderHook } from '@testing-library/react'; +import { waitFor, renderHook } from '@testing-library/react'; import { DeleteConversationParams, @@ -29,21 +29,19 @@ describe('conversations api', () => { }); it('should call api to delete conversation', async () => { - await act(async () => { - const deleteProps = { http, toasts, id: 'test' } as unknown as DeleteConversationParams; + const deleteProps = { http, toasts, id: 'test' } as unknown as DeleteConversationParams; - renderHook(() => deleteConversation(deleteProps)); - await waitFor(() => { - expect(deleteProps.http.fetch).toHaveBeenCalledWith( - '/api/security_ai_assistant/current_user/conversations/test', - { - method: 'DELETE', - signal: undefined, - version: '2023-10-31', - } - ); - expect(toasts.addError).not.toHaveBeenCalled(); - }); + renderHook(() => deleteConversation(deleteProps)); + await waitFor(() => { + expect(deleteProps.http.fetch).toHaveBeenCalledWith( + '/api/security_ai_assistant/current_user/conversations/test', + { + method: 'DELETE', + signal: undefined, + version: '2023-10-31', + } + ); + expect(toasts.addError).not.toHaveBeenCalled(); }); }); @@ -56,20 +54,18 @@ describe('conversations api', () => { }); it('should call api to get conversation', async () => { - await act(async () => { - const getProps = { http, toasts, id: 'test' } as unknown as GetConversationByIdParams; - renderHook(() => getConversationById(getProps)); - await waitFor(() => { - expect(getProps.http.fetch).toHaveBeenCalledWith( - '/api/security_ai_assistant/current_user/conversations/test', - { - method: 'GET', - signal: undefined, - version: '2023-10-31', - } - ); - expect(toasts.addError).not.toHaveBeenCalled(); - }); + const getProps = { http, toasts, id: 'test' } as unknown as GetConversationByIdParams; + renderHook(() => getConversationById(getProps), { legacyRoot: true }); + await waitFor(() => { + expect(getProps.http.fetch).toHaveBeenCalledWith( + '/api/security_ai_assistant/current_user/conversations/test', + { + method: 'GET', + signal: undefined, + version: '2023-10-31', + } + ); + expect(toasts.addError).not.toHaveBeenCalled(); }); }); diff --git a/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/settings/settings_context_menu/settings_context_menu.test.tsx b/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/settings/settings_context_menu/settings_context_menu.test.tsx index 1338f6e0420db..f2ee12e4d4c2a 100644 --- a/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/settings/settings_context_menu/settings_context_menu.test.tsx +++ b/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/assistant/settings/settings_context_menu/settings_context_menu.test.tsx @@ -7,6 +7,7 @@ import { render, screen } from '@testing-library/react'; import React from 'react'; +import { userEvent } from '@testing-library/user-event'; import { mockAssistantAvailability, @@ -29,86 +30,86 @@ describe('SettingsContextMenu', () => { expect(screen.getByRole('button', { name: AI_ASSISTANT_MENU })).toBeInTheDocument(); }); - it('renders all menu items', () => { + it('renders all menu items', async () => { render( ); - screen.getByTestId('chat-context-menu').click(); + await userEvent.click(screen.getByTestId('chat-context-menu')); expect(screen.getByTestId('alerts-to-analyze')).toBeInTheDocument(); expect(screen.getByTestId('anonymize-values')).toBeInTheDocument(); expect(screen.getByTestId('show-citations')).toBeInTheDocument(); expect(screen.getByTestId('clear-chat')).toBeInTheDocument(); }); - it('triggers the reset conversation modal when clicking RESET_CONVERSATION', () => { + it('triggers the reset conversation modal when clicking RESET_CONVERSATION', async () => { render( ); - screen.getByTestId('chat-context-menu').click(); + await userEvent.click(screen.getByTestId('chat-context-menu')); - screen.getByTestId('clear-chat').click(); + await userEvent.click(screen.getByTestId('clear-chat')); expect(screen.getByTestId('reset-conversation-modal')).toBeInTheDocument(); }); - it('disables the anonymize values switch when no anonymized fields are present', () => { + it('disables the anonymize values switch when no anonymized fields are present', async () => { render( ); - screen.getByTestId('chat-context-menu').click(); + await userEvent.click(screen.getByTestId('chat-context-menu')); const anonymizeSwitch = screen.getByTestId('anonymize-switch'); expect(anonymizeSwitch).toBeDisabled(); }); - it('enables the anonymize values switch when no anonymized fields are present', () => { + it('enables the anonymize values switch when no anonymized fields are present', async () => { render( ); - screen.getByTestId('chat-context-menu').click(); + await userEvent.click(screen.getByTestId('chat-context-menu')); const anonymizeSwitch = screen.getByTestId('anonymize-switch'); expect(anonymizeSwitch).not.toBeDisabled(); }); - it('disables the show citations switch when no citations are present', () => { + it('disables the show citations switch when no citations are present', async () => { render( ); - screen.getByTestId('chat-context-menu').click(); + await userEvent.click(screen.getByTestId('chat-context-menu')); const citationsSwitch = screen.getByTestId('citations-switch'); expect(citationsSwitch).toBeDisabled(); }); - it('enables the show citations switch when no citations are present', () => { + it('enables the show citations switch when no citations are present', async () => { render( ); - screen.getByTestId('chat-context-menu').click(); + await userEvent.click(screen.getByTestId('chat-context-menu')); const citationsSwitch = screen.getByTestId('citations-switch'); expect(citationsSwitch).not.toBeDisabled(); }); - it('Navigates to AI settings for non-AI4SOC', () => { + it('Navigates to AI settings for non-AI4SOC', async () => { const mockNavigateToApp = jest.fn(); render( @@ -116,15 +117,15 @@ describe('SettingsContextMenu', () => { ); - screen.getByTestId('chat-context-menu').click(); + await userEvent.click(screen.getByTestId('chat-context-menu')); - screen.getByTestId('ai-assistant-settings').click(); + await userEvent.click(screen.getByTestId('ai-assistant-settings')); expect(mockNavigateToApp).toHaveBeenCalledWith('management', { path: 'kibana/securityAiAssistantManagement', }); }); - it('Navigates to AI settings for AI4SOC', () => { + it('Navigates to AI settings for AI4SOC', async () => { const mockNavigateToApp = jest.fn(); render( { ); - screen.getByTestId('chat-context-menu').click(); + await userEvent.click(screen.getByTestId('chat-context-menu')); - screen.getByTestId('ai-assistant-settings').click(); + await userEvent.click(screen.getByTestId('ai-assistant-settings')); expect(mockNavigateToApp).toHaveBeenCalledWith('securitySolutionUI', { deepLinkId: SecurityPageName.configurationsAiSettings, }); }); - it('Navigates to Knowledge Base for non-AI4SOC', () => { + it('Navigates to Knowledge Base for non-AI4SOC', async () => { const mockNavigateToApp = jest.fn(); render( @@ -154,15 +155,15 @@ describe('SettingsContextMenu', () => { ); - screen.getByTestId('chat-context-menu').click(); + await userEvent.click(screen.getByTestId('chat-context-menu')); - screen.getByTestId('knowledge-base').click(); + await userEvent.click(screen.getByTestId('knowledge-base')); expect(mockNavigateToApp).toHaveBeenCalledWith('management', { path: `kibana/securityAiAssistantManagement?tab=${KNOWLEDGE_BASE_TAB}`, }); }); - it('Navigates to Knowledge Base for AI4SOC', () => { + it('Navigates to Knowledge Base for AI4SOC', async () => { const mockNavigateToApp = jest.fn(); render( { ); - screen.getByTestId('chat-context-menu').click(); + await userEvent.click(screen.getByTestId('chat-context-menu')); - screen.getByTestId('knowledge-base').click(); + await userEvent.click(screen.getByTestId('knowledge-base')); expect(mockNavigateToApp).toHaveBeenCalledWith('securitySolutionUI', { deepLinkId: SecurityPageName.configurationsAiSettings, path: `?tab=${KNOWLEDGE_BASE_TAB}`, diff --git a/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/connectorland/use_load_action_types/index.test.tsx b/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/connectorland/use_load_action_types/index.test.tsx index dd169c9e345e3..5bcecfa4c26f8 100644 --- a/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/connectorland/use_load_action_types/index.test.tsx +++ b/x-pack/platform/packages/shared/kbn-elastic-assistant/impl/connectorland/use_load_action_types/index.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { act, waitFor, renderHook } from '@testing-library/react'; +import { waitFor, renderHook } from '@testing-library/react'; import { useLoadActionTypes, Props } from '.'; import { mockActionTypes } from '../../mock/connectors'; @@ -50,12 +50,10 @@ describe('useLoadActionTypes', () => { ); }); it('should display error toast when api throws error', async () => { - await act(async () => { - const mockHttp = { - get: jest.fn().mockRejectedValue(new Error('this is an error')), - } as unknown as Props['http']; - renderHook(() => useLoadActionTypes({ ...defaultProps, http: mockHttp })); - await waitFor(() => expect(toasts.addError).toHaveBeenCalled()); - }); + const mockHttp = { + get: jest.fn().mockRejectedValue(new Error('this is an error')), + } as unknown as Props['http']; + renderHook(() => useLoadActionTypes({ ...defaultProps, http: mockHttp })); + await waitFor(() => expect(toasts.addError).toHaveBeenCalled()); }); }); diff --git a/x-pack/platform/plugins/private/global_search_bar/public/components/search_bar.test.tsx b/x-pack/platform/plugins/private/global_search_bar/public/components/search_bar.test.tsx index e9faef5e7073d..807b36e19889e 100644 --- a/x-pack/platform/plugins/private/global_search_bar/public/components/search_bar.test.tsx +++ b/x-pack/platform/plugins/private/global_search_bar/public/components/search_bar.test.tsx @@ -73,6 +73,8 @@ describe('SearchBar', () => { const focusAndUpdate = async () => { await act(async () => { (await screen.findByTestId('nav-search-input')).focus(); + }); + act(() => { jest.runAllTimers(); }); }; diff --git a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/flyout/cel_configuration/steps/upload_spec_step/api_definition_input.test.tsx b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/flyout/cel_configuration/steps/upload_spec_step/api_definition_input.test.tsx index baed304189ac9..cad4a31429e83 100644 --- a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/flyout/cel_configuration/steps/upload_spec_step/api_definition_input.test.tsx +++ b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/flyout/cel_configuration/steps/upload_spec_step/api_definition_input.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { act, fireEvent, render, waitFor, type RenderResult } from '@testing-library/react'; +import { act, fireEvent, render, type RenderResult } from '@testing-library/react'; import { TestProvider } from '../../../../../../../mocks/test_provider'; import { ApiDefinitionInput } from './api_definition_input'; @@ -23,9 +23,8 @@ const wrapper: React.FC> = ({ children }) => ( const changeFile = async (input: HTMLElement, file: File) => { await act(async () => { fireEvent.change(input, { target: { files: [file] } }); - await waitFor(() => expect(input).toHaveAttribute('data-loading', 'true')); - await waitFor(() => expect(input).toHaveAttribute('data-loading', 'false')); }); + expect(input).toHaveAttribute('data-loading', 'false'); }; const simpleOpenApiJson = `{"openapi":"3.0.0","info":{"title":"Sample API"},"paths":{"/users":{"get":{"summary":"Returns a list of users.","description":"Optional extended description in CommonMark or HTML.","responses":{"200":{"description":"A JSON array of user names","content":{"application/json":{"schema":{"type":"array","items":{"type":"string"}}}}}}}}}}`; diff --git a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/flyout/cel_configuration/steps/upload_spec_step/upload_spec_step.test.tsx b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/flyout/cel_configuration/steps/upload_spec_step/upload_spec_step.test.tsx index 9356f7856ee7e..f4634731a5d12 100644 --- a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/flyout/cel_configuration/steps/upload_spec_step/upload_spec_step.test.tsx +++ b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/flyout/cel_configuration/steps/upload_spec_step/upload_spec_step.test.tsx @@ -81,13 +81,14 @@ describe('UploadSpecStep', () => { fireEvent.change(result.getByTestId('dataStreamTitleInput'), { target: { value: 'testDataStreamTitle' }, }); - const filepicker = result.getByTestId('apiDefinitionFilePicker'); + }); + const filepicker = result.getByTestId('apiDefinitionFilePicker'); + await act(async () => { fireEvent.change(filepicker, { target: { files: [new File(['...'], 'test.json', { type: 'application/json' })] }, }); - await waitFor(() => expect(filepicker).toHaveAttribute('data-loading', 'true')); - await waitFor(() => expect(filepicker).toHaveAttribute('data-loading', 'false')); }); + await waitFor(() => expect(filepicker).toHaveAttribute('data-loading', 'false')); }); it('analyze button re-enabled', () => { diff --git a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/data_stream_step/generation_modal.test.tsx b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/data_stream_step/generation_modal.test.tsx index 987877efa4755..d17f7beeca429 100644 --- a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/data_stream_step/generation_modal.test.tsx +++ b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/data_stream_step/generation_modal.test.tsx @@ -84,18 +84,16 @@ describe('GenerationModal', () => { let result: RenderResult; const integrationSettingsNonJSON = deepCopy(integrationSettings); beforeEach(async () => { - await act(async () => { - result = render( - , - { wrapper } - ); - await waitFor(() => expect(mockOnComplete).toBeCalled()); - }); + result = render( + , + { wrapper } + ); + await waitFor(() => expect(mockOnComplete).toBeCalled()); }); it('should render generation modal', () => { @@ -167,18 +165,16 @@ describe('GenerationModal', () => { const onCompleteResultsJSON = deepCopy(onCompleteResults); onCompleteResultsJSON.samplesFormat = integrationSettingsJSON.samplesFormat; beforeEach(async () => { - await act(async () => { - result = render( - , - { wrapper } - ); - await waitFor(() => expect(mockOnComplete).toBeCalled()); - }); + result = render( + , + { wrapper } + ); + await waitFor(() => expect(mockOnComplete).toBeCalled()); }); it('should render generation modal', () => { @@ -242,20 +238,18 @@ describe('GenerationModal', () => { throw new Error(errorMessage); }); - await act(async () => { - result = render( - , - { wrapper } - ); - await waitFor(() => - expect(result.queryByTestId('generationErrorCallout')).toBeInTheDocument() - ); - }); + result = render( + , + { wrapper } + ); + await waitFor(() => + expect(result.queryByTestId('generationErrorCallout')).toBeInTheDocument() + ); }); it('should show the error text', () => { @@ -283,8 +277,8 @@ describe('GenerationModal', () => { beforeEach(async () => { await act(async () => { result.getByTestId('retryButton').click(); - await waitFor(() => expect(mockOnComplete).toBeCalled()); }); + await waitFor(() => expect(mockOnComplete).toBeCalled()); }); it('should not render the error callout', () => { @@ -313,20 +307,18 @@ describe('GenerationModal', () => { throw new Error(error); }); - await act(async () => { - result = render( - , - { wrapper } - ); - await waitFor(() => - expect(result.queryByTestId('generationErrorCallout')).toBeInTheDocument() - ); - }); + result = render( + , + { wrapper } + ); + await waitFor(() => + expect(result.queryByTestId('generationErrorCallout')).toBeInTheDocument() + ); }); it('should show the error text', () => { @@ -354,8 +346,8 @@ describe('GenerationModal', () => { beforeEach(async () => { await act(async () => { result.getByTestId('retryButton').click(); - await waitFor(() => expect(mockOnComplete).toBeCalled()); }); + await waitFor(() => expect(mockOnComplete).toBeCalled()); }); it('should not render the error callout', () => { diff --git a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/data_stream_step/sample_logs_input.test.tsx b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/data_stream_step/sample_logs_input.test.tsx index 8932ff5cfee5b..ca3efa7435005 100644 --- a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/data_stream_step/sample_logs_input.test.tsx +++ b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/data_stream_step/sample_logs_input.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { act, fireEvent, render, waitFor, type RenderResult } from '@testing-library/react'; +import { act, fireEvent, render, type RenderResult } from '@testing-library/react'; import { TestProvider } from '../../../../../mocks/test_provider'; import { parseNDJSON, parseJSONArray, SampleLogsInput } from './sample_logs_input'; import { ActionsProvider } from '../../state'; @@ -21,9 +21,8 @@ const wrapper: React.FC> = ({ children }) => ( const changeFile = async (input: HTMLElement, file: File) => { await act(async () => { fireEvent.change(input, { target: { files: [file] } }); - await waitFor(() => expect(input).toHaveAttribute('data-loading', 'true')); - await waitFor(() => expect(input).toHaveAttribute('data-loading', 'false')); }); + expect(input).toHaveAttribute('data-loading', 'false'); }; const simpleNDJSON = `{"message":"test message 1"}\n{"message":"test message 2"}`; diff --git a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/deploy_step/deploy_step.test.tsx b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/deploy_step/deploy_step.test.tsx index a8d975822e1b5..99f55a71c3a18 100644 --- a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/deploy_step/deploy_step.test.tsx +++ b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/deploy_step/deploy_step.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { render, act, type RenderResult, waitFor } from '@testing-library/react'; +import { render, type RenderResult, waitFor } from '@testing-library/react'; import { TestProvider } from '../../../../../mocks/test_provider'; import { DeployStep } from './deploy_step'; import { ActionsProvider } from '../../state'; @@ -70,20 +70,18 @@ describe('DeployStep', () => { describe('when deploy is successful', () => { let result: RenderResult; beforeEach(async () => { - await act(async () => { - result = render( - , - { wrapper } - ); - await waitFor(() => expect(result.queryByTestId('deployStep-loading')).toBeInTheDocument()); - await waitFor(() => - expect(result.queryByTestId('deployStep-loading')).not.toBeInTheDocument() - ); - }); + result = render( + , + { wrapper } + ); + await waitFor(() => expect(result.queryByTestId('deployStep-loading')).toBeInTheDocument()); + await waitFor(() => + expect(result.queryByTestId('deployStep-loading')).not.toBeInTheDocument() + ); }); it('should call build integration api', () => { @@ -136,17 +134,15 @@ describe('DeployStep', () => { mockRunBuildIntegration.mockImplementationOnce(() => { throw new Error(errorMessage); }); - await act(async () => { - result = render( - , - { wrapper } - ); - await waitFor(() => expect(result.queryByTestId('deployStep-error')).toBeInTheDocument()); - }); + result = render( + , + { wrapper } + ); + await waitFor(() => expect(result.queryByTestId('deployStep-error')).toBeInTheDocument()); }); it('should not render success deploy message', () => { @@ -185,17 +181,15 @@ describe('DeployStep', () => { mockRunInstallPackage.mockImplementationOnce(() => { throw new Error(errorMessage); }); - await act(async () => { - result = render( - , - { wrapper } - ); - await waitFor(() => expect(result.queryByTestId('deployStep-error')).toBeInTheDocument()); - }); + result = render( + , + { wrapper } + ); + await waitFor(() => expect(result.queryByTestId('deployStep-error')).toBeInTheDocument()); }); it('should not render success deploy message', () => { diff --git a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/review_step/review_step.test.tsx b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/review_step/review_step.test.tsx index 5fa0c851bb0ef..18c1fadadb1ed 100644 --- a/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/review_step/review_step.test.tsx +++ b/x-pack/platform/plugins/shared/automatic_import/public/components/create_integration/create_automatic_import/steps/review_step/review_step.test.tsx @@ -104,8 +104,8 @@ describe('ReviewStep', () => { beforeEach(async () => { await act(async () => { result.getByTestId('savePipelineButton').click(); - await waitFor(() => expect(mockActions.setIsGenerating).toHaveBeenCalledWith(false)); }); + await waitFor(() => expect(mockActions.setIsGenerating).toHaveBeenCalledWith(false)); }); it('should call setIsGenerating', () => { @@ -131,8 +131,8 @@ describe('ReviewStep', () => { }); await act(async () => { result.getByTestId('savePipelineButton').click(); - await waitFor(() => expect(mockActions.setIsGenerating).toHaveBeenCalledWith(false)); }); + await waitFor(() => expect(mockActions.setIsGenerating).toHaveBeenCalledWith(false)); }); it('should check pipeline', () => { @@ -155,8 +155,8 @@ describe('ReviewStep', () => { }); await act(async () => { result.getByTestId('savePipelineButton').click(); - await waitFor(() => expect(mockActions.setIsGenerating).toHaveBeenCalledWith(false)); }); + await waitFor(() => expect(mockActions.setIsGenerating).toHaveBeenCalledWith(false)); }); it('should check pipeline', () => { diff --git a/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agent_policy/components/actions_menu.test.tsx b/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agent_policy/components/actions_menu.test.tsx index 4df4b4fe912d9..0d16ebf9b21a5 100644 --- a/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agent_policy/components/actions_menu.test.tsx +++ b/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agent_policy/components/actions_menu.test.tsx @@ -5,6 +5,7 @@ * 2.0. */ import React from 'react'; +import { userEvent } from '@testing-library/user-event'; import type { AgentPolicy, PackagePolicy } from '../../../../../../common/types'; import { useAuthz } from '../../../hooks'; @@ -42,7 +43,7 @@ describe('AgentPolicyActionMenu', () => { }); describe('delete action', () => { - it('is enabled when a managed package policy is not present', () => { + it('is enabled when a managed package policy is not present', async () => { const testRenderer = createFleetTestRendererMock(); const agentPolicyWithStandardPackagePolicy: AgentPolicy = { ...baseAgentPolicy, @@ -70,13 +71,13 @@ describe('AgentPolicyActionMenu', () => { ); const agentActionsButton = result.getByTestId('agentActionsBtn'); - agentActionsButton.click(); + await userEvent.click(agentActionsButton); const deleteButton = result.getByTestId('agentPolicyActionMenuDeleteButton'); expect(deleteButton).not.toHaveAttribute('disabled'); }); - it('is disabled when a managed package policy is present', () => { + it('is disabled when a managed package policy is present', async () => { const testRenderer = createFleetTestRendererMock(); const agentPolicyWithManagedPackagePolicy: AgentPolicy = { ...baseAgentPolicy, @@ -104,13 +105,13 @@ describe('AgentPolicyActionMenu', () => { ); const agentActionsButton = result.getByTestId('agentActionsBtn'); - agentActionsButton.click(); + await userEvent.click(agentActionsButton); const deleteButton = result.getByTestId('agentPolicyActionMenuDeleteButton'); expect(deleteButton).toHaveAttribute('disabled'); }); - it('is disabled when agent policy support agentless is true', () => { + it('is disabled when agent policy support agentless is true', async () => { const testRenderer = createFleetTestRendererMock(); const agentlessPolicy: AgentPolicy = { ...baseAgentPolicy, @@ -137,7 +138,7 @@ describe('AgentPolicyActionMenu', () => { const result = testRenderer.render(); const agentActionsButton = result.getByTestId('agentActionsBtn'); - agentActionsButton.click(); + await userEvent.click(agentActionsButton); const deleteButton = result.getByTestId('agentPolicyActionMenuDeleteButton'); expect(deleteButton).not.toHaveAttribute('disabled'); @@ -165,7 +166,7 @@ describe('AgentPolicyActionMenu', () => { }, ], }; - it('is enabled if user is authorized', () => { + it('is enabled if user is authorized', async () => { jest.mocked(useAuthz).mockReturnValue({ fleet: { addAgents: true, @@ -182,12 +183,12 @@ describe('AgentPolicyActionMenu', () => { ); const agentActionsButton = result.getByTestId('agentActionsBtn'); - agentActionsButton.click(); + await userEvent.click(agentActionsButton); const addButton = result.getByTestId('agentPolicyActionMenuAddAgentButton'); expect(addButton).not.toHaveAttribute('disabled'); }); - it('is disabled if user is not authorized', () => { + it('is disabled if user is not authorized', async () => { jest.mocked(useAuthz).mockReturnValue({ fleet: { addAgents: false, @@ -204,13 +205,13 @@ describe('AgentPolicyActionMenu', () => { ); const agentActionsButton = result.getByTestId('agentActionsBtn'); - agentActionsButton.click(); + await userEvent.click(agentActionsButton); const addButton = result.getByTestId('agentPolicyActionMenuAddAgentButton'); expect(addButton).toHaveAttribute('disabled'); }); - it('should remove add agent button when agent policy support agentless is true', () => { + it('should remove add agent button when agent policy support agentless is true', async () => { const testRenderer = createFleetTestRendererMock(); const agentlessPolicy: AgentPolicy = { ...baseAgentPolicy, @@ -237,7 +238,7 @@ describe('AgentPolicyActionMenu', () => { const result = testRenderer.render(); const agentActionsButton = result.getByTestId('agentActionsBtn'); - agentActionsButton.click(); + await userEvent.click(agentActionsButton); const addAgentActionButton = result.queryByTestId('agentPolicyActionMenuAddAgentButton'); expect(addAgentActionButton).toBeNull(); @@ -270,7 +271,7 @@ describe('AgentPolicyActionMenu', () => { }, ], }; - it('is enabled if user is authorized', () => { + it('is enabled if user is authorized', async () => { jest.mocked(useAuthz).mockReturnValue({ fleet: { addAgents: true, @@ -286,13 +287,13 @@ describe('AgentPolicyActionMenu', () => { const result = testRenderer.render(); const agentActionsButton = result.getByTestId('agentActionsBtn'); - agentActionsButton.click(); + await userEvent.click(agentActionsButton); const addButton = result.getByTestId('agentPolicyActionMenuAddAgentButton'); expect(addButton).not.toHaveAttribute('disabled'); }); - it('is disabled if user is only authorized to add agents', () => { + it('is disabled if user is only authorized to add agents', async () => { jest.mocked(useAuthz).mockReturnValue({ fleet: { addAgents: true, @@ -308,12 +309,12 @@ describe('AgentPolicyActionMenu', () => { const result = testRenderer.render(); const agentActionsButton = result.getByTestId('agentActionsBtn'); - agentActionsButton.click(); + await userEvent.click(agentActionsButton); const addButton = result.getByTestId('agentPolicyActionMenuAddAgentButton'); expect(addButton).toHaveAttribute('disabled'); }); - it('is disabled if user is not authorized', () => { + it('is disabled if user is not authorized', async () => { jest.mocked(useAuthz).mockReturnValue({ fleet: { addAgents: false, @@ -328,7 +329,7 @@ describe('AgentPolicyActionMenu', () => { const result = testRenderer.render(); const agentActionsButton = result.getByTestId('agentActionsBtn'); - agentActionsButton.click(); + await userEvent.click(agentActionsButton); const addButton = result.getByTestId('agentPolicyActionMenuAddAgentButton'); expect(addButton).toHaveAttribute('disabled'); diff --git a/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.test.tsx b/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.test.tsx index d4cac73ae049d..c835803fc8687 100644 --- a/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.test.tsx +++ b/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agent_policy/edit_package_policy_page/index.test.tsx @@ -231,7 +231,8 @@ const useMultipleAgentPoliciesMock = useMultipleAgentPolicies as jest.MockedFunc describe('edit package policy page', () => { let testRenderer: TestRenderer; let renderResult: ReturnType; - const render = () => (renderResult = testRenderer.render()); + const render = () => + (renderResult = testRenderer.render(, { legacyRoot: true })); beforeEach(() => { testRenderer = createFleetTestRendererMock(); diff --git a/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/filter_dataset.test.tsx b/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/filter_dataset.test.tsx index c06f012c77b58..c566c43273ed5 100644 --- a/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/filter_dataset.test.tsx +++ b/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agents/agent_details_page/components/agent_logs/filter_dataset.test.tsx @@ -5,11 +5,12 @@ * 2.0. */ import React from 'react'; -import { render, act, fireEvent } from '@testing-library/react'; +import { render } from '@testing-library/react'; import { __IntlProvider as IntlProvider } from '@kbn/i18n-react'; import { DatasetFilter } from './filter_dataset'; +import userEvent from '@testing-library/user-event'; const renderComponent = (props: React.ComponentProps) => { return render( @@ -49,10 +50,8 @@ describe('DatasetFilter', () => { onToggleDataset: () => {}, }); - it('Renders all statuses', () => { - act(() => { - fireEvent.click(getByRole('button')); - }); + it('Renders all statuses', async () => { + await userEvent.click(getByRole('button')); expect(getByText('elastic_agent')).toBeInTheDocument(); expect(getByText('elastic_agent.filebeat')).toBeInTheDocument(); diff --git a/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agents/agent_list_page/components/filter_bar/tags_filter.test.tsx b/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agents/agent_list_page/components/filter_bar/tags_filter.test.tsx index 4725939ec9132..35a3ca6ccfd23 100644 --- a/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agents/agent_list_page/components/filter_bar/tags_filter.test.tsx +++ b/x-pack/platform/plugins/shared/fleet/public/applications/fleet/sections/agents/agent_list_page/components/filter_bar/tags_filter.test.tsx @@ -6,6 +6,7 @@ */ import React from 'react'; +import { userEvent } from '@testing-library/user-event'; import { createFleetTestRendererMock } from '../../../../../../../mock'; @@ -29,9 +30,9 @@ describe('TagsFilter', () => { }; const { getByText, getByTestId } = render(props); const filterButton = getByTestId('agentList.tagsFilter'); - filterButton.click(); + await userEvent.click(filterButton); const tag = getByText('tag1'); - tag.click(); + await userEvent.click(tag); expect(onSelectedTagsChange).toHaveBeenCalledWith(['tag2', 'tag3']); }); }); diff --git a/x-pack/platform/plugins/shared/fleet/public/applications/integrations/sections/epm/screens/detail/index.test.tsx b/x-pack/platform/plugins/shared/fleet/public/applications/integrations/sections/epm/screens/detail/index.test.tsx index 400c5f3a5aa6d..0fa5398b16486 100644 --- a/x-pack/platform/plugins/shared/fleet/public/applications/integrations/sections/epm/screens/detail/index.test.tsx +++ b/x-pack/platform/plugins/shared/fleet/public/applications/integrations/sections/epm/screens/detail/index.test.tsx @@ -62,7 +62,7 @@ describe('When on integration detail', () => { beforeEach(async () => { testRenderer = createIntegrationsTestRendererMock(); mockedApi = mockApiCalls(testRenderer.startServices.http); - act(() => testRenderer.mountHistory.push(detailPageUrlPath)); + await act(() => testRenderer.mountHistory.push(detailPageUrlPath)); }); describe('and the package is installed', () => { @@ -76,11 +76,11 @@ describe('When on integration detail', () => { }, TESTS_TIMEOUT); it('should display agent policy usage count', async () => { - expect(renderResult.queryByTestId('agentPolicyCount')).not.toBeNull(); + expect(await renderResult.findByTestId('agentPolicyCount')).not.toBeNull(); }); it('should show the Policies tab', async () => { - expect(renderResult.queryByTestId('tab-policies')).not.toBeNull(); + expect(await renderResult.findByTestId('tab-policies')).not.toBeNull(); }); }); diff --git a/x-pack/platform/plugins/shared/fleet/public/components/uninstall_command_flyout/uninstall_command_flyout.test.tsx b/x-pack/platform/plugins/shared/fleet/public/components/uninstall_command_flyout/uninstall_command_flyout.test.tsx index cabefda61289d..24584b987dd8d 100644 --- a/x-pack/platform/plugins/shared/fleet/public/components/uninstall_command_flyout/uninstall_command_flyout.test.tsx +++ b/x-pack/platform/plugins/shared/fleet/public/components/uninstall_command_flyout/uninstall_command_flyout.test.tsx @@ -31,6 +31,7 @@ import type { RequestError } from '../../hooks'; import { UninstallCommandFlyout } from './uninstall_command_flyout'; import type { UninstallCommandTarget } from './types'; +import userEvent from '@testing-library/user-event'; jest.mock('../../hooks/use_request/uninstall_tokens', () => ({ useGetUninstallToken: jest.fn(), @@ -156,10 +157,10 @@ describe('UninstallCommandFlyout', () => { ); }); - it('when user selects Windows, it renders commands for Windows', () => { + it('when user selects Windows, it renders commands for Windows', async () => { const renderResult = render(); - renderResult.getByTestId('windows').click(); + await userEvent.click(renderResult.getByTestId('windows')); const uninstallInstructions = renderResult.getByTestId( 'uninstall-commands-flyout-code-block' diff --git a/x-pack/platform/plugins/shared/lens/public/app_plugin/app.test.tsx b/x-pack/platform/plugins/shared/lens/public/app_plugin/app.test.tsx index 4646d680999be..3b1704388f948 100644 --- a/x-pack/platform/plugins/shared/lens/public/app_plugin/app.test.tsx +++ b/x-pack/platform/plugins/shared/lens/public/app_plugin/app.test.tsx @@ -419,12 +419,14 @@ describe('Lens App', () => { references: [{ type: 'index-pattern', id: '1', name: 'index-pattern-0' }], }); - await lensStore.dispatch( - setState({ - query, - persistedDoc: document, - }) - ); + await act(async () => { + await lensStore.dispatch( + setState({ + query, + persistedDoc: document, + }) + ); + }); expect(services.navigation.ui.AggregateQueryTopNavMenu).toHaveBeenCalledWith( expect.objectContaining({ diff --git a/x-pack/platform/plugins/shared/lens/public/app_plugin/settings_menu.test.tsx b/x-pack/platform/plugins/shared/lens/public/app_plugin/settings_menu.test.tsx index 62a1d94d9b877..ab15ebd5a47c7 100644 --- a/x-pack/platform/plugins/shared/lens/public/app_plugin/settings_menu.test.tsx +++ b/x-pack/platform/plugins/shared/lens/public/app_plugin/settings_menu.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { renderWithReduxStore } from '../mocks'; import { SettingsMenu } from './settings_menu'; import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; describe('settings menu', () => { const onCloseMock = jest.fn(); @@ -23,9 +24,9 @@ describe('settings menu', () => { /> ); - const toggleAutoApply = () => { + const toggleAutoApply = async () => { const autoApplyToggle = screen.getByTestId('lnsToggleAutoApply'); - autoApplyToggle.click(); + await userEvent.click(autoApplyToggle); }; const isAutoApplyOn = () => { @@ -46,7 +47,7 @@ describe('settings menu', () => { it('should call onClose when popover closes after toggling', async () => { const { toggleAutoApply } = renderSettingsMenu(); - toggleAutoApply(); + await toggleAutoApply(); await waitFor(() => expect(onCloseMock).toHaveBeenCalledTimes(1)); }); @@ -56,10 +57,10 @@ describe('settings menu', () => { expect(isAutoApplyOn()).toBeTruthy(); - toggleAutoApply(); + await toggleAutoApply(); expect(isAutoApplyOn()).toBeFalsy(); - toggleAutoApply(); + await toggleAutoApply(); expect(isAutoApplyOn()).toBeTruthy(); }); }); diff --git a/x-pack/platform/plugins/shared/lens/public/editor_frame_service/editor_frame/editor_frame.test.tsx b/x-pack/platform/plugins/shared/lens/public/editor_frame_service/editor_frame/editor_frame.test.tsx index ad53002a1b0cb..ae22fa6778948 100644 --- a/x-pack/platform/plugins/shared/lens/public/editor_frame_service/editor_frame/editor_frame.test.tsx +++ b/x-pack/platform/plugins/shared/lens/public/editor_frame_service/editor_frame/editor_frame.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { screen, within } from '@testing-library/react'; +import { act, screen, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { EditorFrame, EditorFrameProps } from './editor_frame'; @@ -193,7 +193,10 @@ describe('editor_frame', () => { expect(queryDataPanel()).not.toBeInTheDocument(); expect(queryLayerPanel()).not.toBeInTheDocument(); - simulateLoadingDatasource(); + act(() => { + simulateLoadingDatasource(); + }); + expect(mockVisualization.getConfiguration).toHaveBeenCalledWith( expect.objectContaining({ state: 'initialState' }) ); @@ -215,16 +218,18 @@ describe('editor_frame', () => { const { store } = renderEditorFrame(); const updatedState = 'updatedVisState'; - store.dispatch( - setState({ - visualization: { - activeId: mockVisualization.id, - state: updatedState, - }, - }) - ); + act(() => { + store.dispatch( + setState({ + visualization: { + activeId: mockVisualization.id, + state: updatedState, + }, + }) + ); + }); - expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(3); + expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(4); expect(mockVisualization.getConfiguration).toHaveBeenLastCalledWith( expect.objectContaining({ state: updatedState, @@ -244,7 +249,9 @@ describe('editor_frame', () => { title: 'shazm', }; - setDatasourceState(updatedState); + act(() => { + setDatasourceState(updatedState); + }); expect(mockDatasource.DataPanelComponent).toHaveBeenCalledTimes(1); expect(mockDatasource.DataPanelComponent).toHaveBeenLastCalledWith( @@ -274,7 +281,9 @@ describe('editor_frame', () => { const setDatasourceState = (mockDatasource.DataPanelComponent as jest.Mock).mock.calls[0][0] .setState; - setDatasourceState('newState'); + act(() => { + setDatasourceState('newState'); + }); expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(1); expect(mockVisualization.getConfiguration).toHaveBeenCalledWith( diff --git a/x-pack/platform/plugins/shared/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.test.tsx b/x-pack/platform/plugins/shared/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.test.tsx index c5cabaa053c4b..8e88d6b329d5e 100644 --- a/x-pack/platform/plugins/shared/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.test.tsx +++ b/x-pack/platform/plugins/shared/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.test.tsx @@ -17,9 +17,10 @@ import { WorkspacePanelWrapper } from './workspace_panel_wrapper'; import { updateVisualizationState, LensAppState } from '../../../state_management'; import { setChangesApplied } from '../../../state_management/lens_slice'; import { LensInspector } from '../../../lens_inspector_service'; -import { screen } from '@testing-library/react'; +import { act, screen } from '@testing-library/react'; import { faker } from '@faker-js/faker'; import { SettingsMenu } from '../../../app_plugin/settings_menu'; +import userEvent from '@testing-library/user-event'; describe('workspace_panel_wrapper', () => { let mockVisualization: jest.Mocked; @@ -62,9 +63,9 @@ describe('workspace_panel_wrapper', () => { return screen.queryByTestId('lnsApplyChanges__toolbar'); }; - const toggleAutoApply = () => { + const toggleAutoApply = async () => { const autoApplyToggle = screen.getByTestId('lnsToggleAutoApply'); - autoApplyToggle.click(); + await userEvent.click(autoApplyToggle); }; const isAutoApplyOn = () => { @@ -125,41 +126,53 @@ describe('workspace_panel_wrapper', () => { describe('auto-apply controls', () => { it('shows and hides apply-changes button depending on whether auto-apply is enabled', async () => { const { toggleAutoApply, getApplyChangesToolbar } = renderWorkspacePanelWrapper(); - toggleAutoApply(); + await toggleAutoApply(); expect(getApplyChangesToolbar()).toBeInTheDocument(); - toggleAutoApply(); + await toggleAutoApply(); expect(getApplyChangesToolbar()).not.toBeInTheDocument(); - toggleAutoApply(); + await toggleAutoApply(); expect(getApplyChangesToolbar()).toBeInTheDocument(); }); - it('apply-changes button applies changes', () => { + it('apply-changes button applies changes', async () => { const { store, toggleAutoApply, getApplyChangesToolbar, editVisualization } = renderWorkspacePanelWrapper(); - toggleAutoApply(); + await toggleAutoApply(); expect(getApplyChangesToolbar()).toBeDisabled(); // make a change - editVisualization(); + act(() => { + editVisualization(); + }); + // // simulate workspace panel behavior - store.dispatch(setChangesApplied(false)); + act(() => { + store.dispatch(setChangesApplied(false)); + }); expect(getApplyChangesToolbar()).not.toBeDisabled(); // // simulate workspace panel behavior - store.dispatch(setChangesApplied(true)); + act(() => { + store.dispatch(setChangesApplied(true)); + }); expect(getApplyChangesToolbar()).toBeDisabled(); }); - it('enabling auto apply while having unapplied changes works', () => { + it('enabling auto apply while having unapplied changes works', async () => { const { store, toggleAutoApply, getApplyChangesToolbar, editVisualization } = renderWorkspacePanelWrapper(); - toggleAutoApply(); - editVisualization(); + await toggleAutoApply(); + act(() => { + editVisualization(); + }); + // simulate workspace panel behavior - store.dispatch(setChangesApplied(false)); + act(() => { + store.dispatch(setChangesApplied(false)); + }); expect(getApplyChangesToolbar()).not.toBeDisabled(); - toggleAutoApply(); + await toggleAutoApply(); expect(getApplyChangesToolbar()).not.toBeInTheDocument(); }); }); diff --git a/x-pack/platform/plugins/shared/lens/public/visualizations/datatable/components/table_basic.test.tsx b/x-pack/platform/plugins/shared/lens/public/visualizations/datatable/components/table_basic.test.tsx index e1ca865e1b450..ece95066bb889 100644 --- a/x-pack/platform/plugins/shared/lens/public/visualizations/datatable/components/table_basic.test.tsx +++ b/x-pack/platform/plugins/shared/lens/public/visualizations/datatable/components/table_basic.test.tsx @@ -690,7 +690,7 @@ describe('DatatableComponent', () => { renderDatatableComponent(); - expect(getCellColorFn).toBeCalledTimes(2); // 2 initial renders of table + expect(getCellColorFn).toBeCalledTimes(3); // 3 initial renders of table }); test('caches getCellColorFn by columnId with transpose columns', () => { @@ -717,7 +717,7 @@ describe('DatatableComponent', () => { }, }); - expect(getCellColorFn).toBeCalledTimes(2); // 2 initial renders of table + expect(getCellColorFn).toBeCalledTimes(3); // 3 initial renders of table }); }); diff --git a/x-pack/platform/plugins/shared/lens/public/visualizations/metric/toolbar/titles_and_text_popover.test.tsx b/x-pack/platform/plugins/shared/lens/public/visualizations/metric/toolbar/titles_and_text_popover.test.tsx index 22c6a0d77617d..6a7b9f92903d2 100644 --- a/x-pack/platform/plugins/shared/lens/public/visualizations/metric/toolbar/titles_and_text_popover.test.tsx +++ b/x-pack/platform/plugins/shared/lens/public/visualizations/metric/toolbar/titles_and_text_popover.test.tsx @@ -54,7 +54,10 @@ describe('TitlesAndTextPopover', () => { const renderToolbarOptions = (state: MetricVisualizationState) => { return { - ...render(), + ...render(, { + // fails in concurrent mode + legacyRoot: true, + }), }; }; diff --git a/x-pack/platform/plugins/shared/security/public/account_management/user_profile/user_profile.test.tsx b/x-pack/platform/plugins/shared/security/public/account_management/user_profile/user_profile.test.tsx index 1bc714599c711..0a39d3f3e4709 100644 --- a/x-pack/platform/plugins/shared/security/public/account_management/user_profile/user_profile.test.tsx +++ b/x-pack/platform/plugins/shared/security/public/account_management/user_profile/user_profile.test.tsx @@ -181,6 +181,8 @@ describe('useUserProfileForm', () => { await act(async () => { await result.current.setFieldValue('user.full_name', 'Another Name'); + }); + await act(async () => { await result.current.submitForm(); }); @@ -305,6 +307,9 @@ describe('useUserProfileForm', () => { await act(async () => { await result.current.setFieldValue('data.userSettings.darkMode', 'dark'); + }); + + await act(async () => { await result.current.submitForm(); }); @@ -405,6 +410,9 @@ describe('useUserProfileForm', () => { await act(async () => { await result.current.setFieldValue('data.userSettings.contrastMode', 'high'); // default value is 'system' + }); + + await act(async () => { await result.current.submitForm(); }); diff --git a/x-pack/platform/plugins/shared/spaces/public/management/edit_space/edit_space_general_tab.test.tsx b/x-pack/platform/plugins/shared/spaces/public/management/edit_space/edit_space_general_tab.test.tsx index f2ea7d05ec498..91f93fea240c9 100644 --- a/x-pack/platform/plugins/shared/spaces/public/management/edit_space/edit_space_general_tab.test.tsx +++ b/x-pack/platform/plugins/shared/spaces/public/management/edit_space/edit_space_general_tab.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; @@ -190,24 +190,22 @@ describe('EditSpaceSettings', () => { ); - await act(async () => { - // update the space name - const nameInput = screen.getByTestId('addSpaceName'); - fireEvent.change(nameInput, { target: { value: 'Updated Name Of Space' } }); + // update the space name + const nameInput = screen.getByTestId('addSpaceName'); + fireEvent.change(nameInput, { target: { value: 'Updated Name Of Space' } }); - expect(screen.queryByTestId('space-edit-page-user-impact-warning')).not.toBeInTheDocument(); - expect(screen.queryByTestId('confirmModalTitleText')).not.toBeInTheDocument(); + expect(screen.queryByTestId('space-edit-page-user-impact-warning')).not.toBeInTheDocument(); + expect(screen.queryByTestId('confirmModalTitleText')).not.toBeInTheDocument(); - const updateButton = await screen.findByTestId('save-space-button'); // appears via re-render - await userEvent.click(updateButton); + const updateButton = await screen.findByTestId('save-space-button'); // appears via re-render + await userEvent.click(updateButton); - expect(updateSpaceSpy).toHaveBeenCalledWith({ - ...spaceToUpdate, - name: 'Updated Name Of Space', - initials: 'UN', - imageUrl: '', - color: '#FFC7DB', - }); + expect(updateSpaceSpy).toHaveBeenCalledWith({ + ...spaceToUpdate, + name: 'Updated Name Of Space', + initials: 'UN', + imageUrl: '', + color: '#FFC7DB', }); expect(navigateSpy).toHaveBeenCalledTimes(1); @@ -236,15 +234,13 @@ describe('EditSpaceSettings', () => { ); - await act(async () => { - const deleteButton = screen.getByTestId('delete-space-button'); - await userEvent.click(deleteButton); + const deleteButton = screen.getByTestId('delete-space-button'); + await userEvent.click(deleteButton); - const confirmButton = await screen.findByTestId('confirmModalConfirmButton'); // click delete confirm - await userEvent.click(confirmButton); + const confirmButton = await screen.findByTestId('confirmModalConfirmButton'); // click delete confirm + await userEvent.click(confirmButton); - expect(deleteSpaceSpy).toHaveBeenCalledWith(spaceToDelete); - }); + expect(deleteSpaceSpy).toHaveBeenCalledWith(spaceToDelete); }); it('sets calculated fields for existing spaces', async () => { @@ -274,21 +270,19 @@ describe('EditSpaceSettings', () => { ); - await act(async () => { - // update the space name - const nameInput = screen.getByTestId('addSpaceName'); - fireEvent.change(nameInput, { target: { value: 'Updated Existing Space' } }); + // update the space name + const nameInput = screen.getByTestId('addSpaceName'); + fireEvent.change(nameInput, { target: { value: 'Updated Existing Space' } }); - const updateButton = await screen.findByTestId('save-space-button'); // appears via re-render - await userEvent.click(updateButton); + const updateButton = await screen.findByTestId('save-space-button'); // appears via re-render + await userEvent.click(updateButton); - expect(updateSpaceSpy).toHaveBeenCalledWith({ - ...spaceToUpdate, - name: 'Updated Existing Space', - color: '#FFC7DB', - initials: 'UE', - imageUrl: '', - }); + expect(updateSpaceSpy).toHaveBeenCalledWith({ + ...spaceToUpdate, + name: 'Updated Existing Space', + color: '#FFC7DB', + initials: 'UE', + imageUrl: '', }); }); @@ -317,30 +311,28 @@ describe('EditSpaceSettings', () => { ); // update the space solution view - await act(async () => { - const solutionViewPicker = screen.getByTestId('solutionViewSelect'); - await userEvent.click(solutionViewPicker); + const solutionViewPicker = screen.getByTestId('solutionViewSelect'); + await userEvent.click(solutionViewPicker); - const esSolutionOption = await screen.findByTestId('solutionViewEsOption'); // appears via re-render - await userEvent.click(esSolutionOption); + const esSolutionOption = await screen.findByTestId('solutionViewEsOption'); // appears via re-render + await userEvent.click(esSolutionOption); - expect(screen.getByTestId('space-edit-page-user-impact-warning')).toBeInTheDocument(); - expect(screen.queryByTestId('confirmModalTitleText')).not.toBeInTheDocument(); + expect(screen.getByTestId('space-edit-page-user-impact-warning')).toBeInTheDocument(); + expect(screen.queryByTestId('confirmModalTitleText')).not.toBeInTheDocument(); - const updateButton = screen.getByTestId('save-space-button'); - await userEvent.click(updateButton); + const updateButton = screen.getByTestId('save-space-button'); + await userEvent.click(updateButton); - expect(screen.getByTestId('confirmModalTitleText')).toBeInTheDocument(); + expect(screen.getByTestId('confirmModalTitleText')).toBeInTheDocument(); - const confirmButton = screen.getByTestId('confirmModalConfirmButton'); - await userEvent.click(confirmButton); + const confirmButton = screen.getByTestId('confirmModalConfirmButton'); + await userEvent.click(confirmButton); - await waitFor(() => { - expect(updateSpaceSpy).toHaveBeenCalledWith({ - ...spaceToUpdate, - imageUrl: '', - solution: 'es', - }); + await waitFor(() => { + expect(updateSpaceSpy).toHaveBeenCalledWith({ + ...spaceToUpdate, + imageUrl: '', + solution: 'es', }); }); @@ -382,32 +374,30 @@ describe('EditSpaceSettings', () => { ); // update the space visible features - await act(async () => { - const feature1Checkbox = screen.getByTestId('featureCheckbox_feature-1'); - expect(feature1Checkbox).toBeChecked(); + const feature1Checkbox = screen.getByTestId('featureCheckbox_feature-1'); + expect(feature1Checkbox).toBeChecked(); - await userEvent.click(feature1Checkbox); - await waitFor(() => { - expect(feature1Checkbox).not.toBeChecked(); - }); + await userEvent.click(feature1Checkbox); + await waitFor(() => { + expect(feature1Checkbox).not.toBeChecked(); + }); - expect(screen.getByTestId('space-edit-page-user-impact-warning')).toBeInTheDocument(); - expect(screen.queryByTestId('confirmModalTitleText')).not.toBeInTheDocument(); + expect(screen.getByTestId('space-edit-page-user-impact-warning')).toBeInTheDocument(); + expect(screen.queryByTestId('confirmModalTitleText')).not.toBeInTheDocument(); - const updateButton = screen.getByTestId('save-space-button'); - await userEvent.click(updateButton); + const updateButton = screen.getByTestId('save-space-button'); + await userEvent.click(updateButton); - expect(screen.getByTestId('confirmModalTitleText')).toBeInTheDocument(); + expect(screen.getByTestId('confirmModalTitleText')).toBeInTheDocument(); - const confirmButton = screen.getByTestId('confirmModalConfirmButton'); - await userEvent.click(confirmButton); + const confirmButton = screen.getByTestId('confirmModalConfirmButton'); + await userEvent.click(confirmButton); - await waitFor(() => { - expect(updateSpaceSpy).toHaveBeenCalledWith({ - ...spaceToUpdate, - imageUrl: '', - disabledFeatures: ['feature-1'], - }); + await waitFor(() => { + expect(updateSpaceSpy).toHaveBeenCalledWith({ + ...spaceToUpdate, + imageUrl: '', + disabledFeatures: ['feature-1'], }); }); @@ -451,9 +441,7 @@ describe('EditSpaceSettings', () => { // update the space visible features const feature1Checkbox = screen.getByTestId('featureCheckbox_feature-1'); expect(feature1Checkbox).toBeChecked(); - await act(async () => { - await userEvent.click(feature1Checkbox); - }); + await userEvent.click(feature1Checkbox); await waitFor(() => { expect(feature1Checkbox).not.toBeChecked(); }); @@ -462,16 +450,12 @@ describe('EditSpaceSettings', () => { expect(screen.queryByTestId('confirmModalTitleText')).not.toBeInTheDocument(); const updateButton = screen.getByTestId('save-space-button'); - await act(async () => { - await userEvent.click(updateButton); - }); + await userEvent.click(updateButton); expect(screen.getByTestId('confirmModalTitleText')).toBeInTheDocument(); const confirmButton = screen.getByTestId('confirmModalConfirmButton'); - await act(async () => { - await userEvent.click(confirmButton); - }); + await userEvent.click(confirmButton); await waitFor(() => { expect(updateSpaceSpy).toHaveBeenCalledWith({ @@ -519,45 +503,39 @@ describe('EditSpaceSettings', () => { ); // customize the space visible features to disable feature-1 - await act(async () => { - const feature1Checkbox = screen.getByTestId('featureCheckbox_feature-1'); - expect(feature1Checkbox).toBeChecked(); - - await userEvent.click(feature1Checkbox); - await waitFor(() => { - expect(feature1Checkbox).not.toBeChecked(); - }); + const feature1Checkbox = screen.getByTestId('featureCheckbox_feature-1'); + expect(feature1Checkbox).toBeChecked(); - expect(screen.getByTestId('space-edit-page-user-impact-warning')).toBeInTheDocument(); - expect(screen.queryByTestId('confirmModalTitleText')).not.toBeInTheDocument(); + await userEvent.click(feature1Checkbox); + await waitFor(() => { + expect(feature1Checkbox).not.toBeChecked(); }); + expect(screen.getByTestId('space-edit-page-user-impact-warning')).toBeInTheDocument(); + expect(screen.queryByTestId('confirmModalTitleText')).not.toBeInTheDocument(); + // change the selected solution view to es - await act(async () => { - const solutionViewPicker = screen.getByTestId('solutionViewSelect'); - await userEvent.click(solutionViewPicker); + const solutionViewPicker = screen.getByTestId('solutionViewSelect'); + await userEvent.click(solutionViewPicker); - const esSolutionOption = await screen.findByTestId('solutionViewEsOption'); // appears via re-render - await userEvent.click(esSolutionOption); - }); + const esSolutionOption = await screen.findByTestId('solutionViewEsOption'); // appears via re-render + await userEvent.click(esSolutionOption); // perform the save - await act(async () => { - const updateButton = screen.getByTestId('save-space-button'); - await userEvent.click(updateButton); - - expect(screen.getByTestId('confirmModalTitleText')).toBeInTheDocument(); - - const confirmButton = screen.getByTestId('confirmModalConfirmButton'); - await userEvent.click(confirmButton); - - await waitFor(() => { - expect(updateSpaceSpy).toHaveBeenCalledWith({ - ...spaceToUpdate, - imageUrl: '', - solution: 'es', - disabledFeatures: [], // "feature-1" became deselected - }); + const updateButton = screen.getByTestId('save-space-button'); + await userEvent.click(updateButton); + + expect(screen.getByTestId('confirmModalTitleText')).toBeInTheDocument(); + + const confirmButton = screen.getByTestId('confirmModalConfirmButton'); + await userEvent.click(confirmButton); + + await waitFor(() => { + expect(updateSpaceSpy).toHaveBeenCalledWith({ + ...spaceToUpdate, + imageUrl: '', + solution: 'es', + disabledFeatures: [], // "feature-1" became deselected }); }); diff --git a/x-pack/platform/plugins/shared/stack_connectors/public/connector_types/es_index/es_index_connector.test.tsx b/x-pack/platform/plugins/shared/stack_connectors/public/connector_types/es_index/es_index_connector.test.tsx index e55ac7546d471..bc8d45a653f8d 100644 --- a/x-pack/platform/plugins/shared/stack_connectors/public/connector_types/es_index/es_index_connector.test.tsx +++ b/x-pack/platform/plugins/shared/stack_connectors/public/connector_types/es_index/es_index_connector.test.tsx @@ -354,9 +354,7 @@ describe('IndexActionConnectorFields', () => { ); - await act(async () => { - await userEvent.click(getByTestId('form-test-provide-submit')); - }); + await userEvent.click(getByTestId('form-test-provide-submit')); expect(onSubmit).toBeCalledWith({ data: { @@ -399,9 +397,7 @@ describe('IndexActionConnectorFields', () => { ); - await act(async () => { - await userEvent.click(getByTestId('form-test-provide-submit')); - }); + await userEvent.click(getByTestId('form-test-provide-submit')); expect(onSubmit).toBeCalledWith({ data: { @@ -439,9 +435,7 @@ describe('IndexActionConnectorFields', () => { ); - await act(async () => { - await userEvent.click(getByTestId('form-test-provide-submit')); - }); + await userEvent.click(getByTestId('form-test-provide-submit')); expect(onSubmit).toBeCalledWith({ data: {}, diff --git a/x-pack/platform/plugins/shared/stack_connectors/public/connector_types/lib/servicenow/update_connector.test.tsx b/x-pack/platform/plugins/shared/stack_connectors/public/connector_types/lib/servicenow/update_connector.test.tsx index 8d0b854797680..9dba75b461679 100644 --- a/x-pack/platform/plugins/shared/stack_connectors/public/connector_types/lib/servicenow/update_connector.test.tsx +++ b/x-pack/platform/plugins/shared/stack_connectors/public/connector_types/lib/servicenow/update_connector.test.tsx @@ -11,7 +11,7 @@ import userEvent from '@testing-library/user-event'; import { mountWithIntl } from '@kbn/test-jest-helpers'; import { Props, UpdateConnector } from './update_connector'; import { act } from 'react-dom/test-utils'; -import { render, act as reactAct, waitFor } from '@testing-library/react'; +import { render, waitFor } from '@testing-library/react'; jest.mock('@kbn/triggers-actions-ui-plugin/public/common/lib/kibana'); @@ -235,16 +235,14 @@ describe('UpdateConnector renders', () => { expect(onConfirm).not.toHaveBeenCalled(); - await reactAct(async () => { - const urlInput = getByTestId('credentialsApiUrlFromInput'); - const usernameInput = getByTestId('connector-servicenow-username-form-input'); - const passwordInput = getByTestId('connector-servicenow-password-form-input'); + const urlInput = getByTestId('credentialsApiUrlFromInput'); + const usernameInput = getByTestId('connector-servicenow-username-form-input'); + const passwordInput = getByTestId('connector-servicenow-password-form-input'); - await userEvent.type(urlInput, 'https://example.com', { delay: 100 }); - await userEvent.type(usernameInput, 'user', { delay: 100 }); - await userEvent.type(passwordInput, 'pass', { delay: 100 }); - await userEvent.click(getByTestId('snUpdateInstallationSubmit')); - }); + await userEvent.type(urlInput, 'https://example.com', { delay: 100 }); + await userEvent.type(usernameInput, 'user', { delay: 100 }); + await userEvent.type(passwordInput, 'pass', { delay: 100 }); + await userEvent.click(getByTestId('snUpdateInstallationSubmit')); // Wait for click event to be processed await waitFor(() => expect(onConfirm).toHaveBeenCalled(), { timeout: 3000 }); diff --git a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/action_connector_form/action_type_form.test.tsx b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/action_connector_form/action_type_form.test.tsx index 2480beb6b919d..d53dd85781810 100644 --- a/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/action_connector_form/action_type_form.test.tsx +++ b/x-pack/platform/plugins/shared/triggers_actions_ui/public/application/sections/action_connector_form/action_type_form.test.tsx @@ -29,6 +29,7 @@ import { } from '@kbn/alerting-plugin/common'; import { AlertConsumers } from '@kbn/rule-data-utils'; import { transformActionVariables } from '@kbn/alerts-ui-shared/src/action_variables/transforms'; +import userEvent from '@testing-library/user-event'; const CUSTOM_NOTIFY_WHEN_OPTIONS: NotifyWhenSelectOptions[] = [ { @@ -112,6 +113,10 @@ jest.mock('../../hooks/use_rule_alert_fields', () => ({ describe('action_type_form', () => { afterEach(() => { jest.clearAllMocks(); + + // some tests rely on fake timers, so we need to clear them + jest.clearAllTimers(); + jest.useRealTimers(); }); useGetRuleTypesPermissions.mockReturnValue({ @@ -474,10 +479,8 @@ describe('action_type_form', () => { expect(summaryOrPerRuleSelect).toBeTruthy(); const button = wrapper.getByText('For each alert'); - button.click(); - await act(async () => { - wrapper.getByText('Summary of alerts').click(); - }); + await userEvent.click(button); + await userEvent.click(wrapper.getByText('Summary of alerts')); expect(mockTransformActionVariables.mock.calls).toEqual([ [ @@ -604,19 +607,17 @@ describe('action_type_form', () => { ); - wrapper.getByTestId('notifyWhenSelect').click(); - await act(async () => { - expect(wrapper.queryByText('On status changes')).not.toBeTruthy(); - expect(wrapper.queryByText('On check intervals')).not.toBeTruthy(); - expect(wrapper.queryByText('On custom action intervals')).not.toBeTruthy(); + await userEvent.click(wrapper.getByTestId('notifyWhenSelect')); + expect(wrapper.queryByText('On status changes')).not.toBeTruthy(); + expect(wrapper.queryByText('On check intervals')).not.toBeTruthy(); + expect(wrapper.queryByText('On custom action intervals')).not.toBeTruthy(); - expect(wrapper.getAllByText('Per rule run')).toBeTruthy(); - expect(wrapper.getAllByText('Custom frequency')).toBeTruthy(); + expect(wrapper.getAllByText('Per rule run')).toBeTruthy(); + expect(wrapper.getAllByText('Custom frequency')).toBeTruthy(); - expect(wrapper.queryByTestId('onActionGroupChange')).not.toBeTruthy(); - expect(wrapper.getByTestId('onActiveAlert')).toBeTruthy(); - expect(wrapper.getByTestId('onThrottleInterval')).toBeTruthy(); - }); + expect(wrapper.queryByTestId('onActionGroupChange')).not.toBeTruthy(); + expect(wrapper.getByTestId('onActiveAlert')).toBeTruthy(); + expect(wrapper.getByTestId('onThrottleInterval')).toBeTruthy(); }); it('should have only "Per rule run" notify when option for "For each alert" actions', async () => { @@ -658,19 +659,17 @@ describe('action_type_form', () => { ); - wrapper.getByTestId('notifyWhenSelect').click(); - await act(async () => { - expect(wrapper.queryByText('On status changes')).not.toBeTruthy(); - expect(wrapper.queryByText('On check intervals')).not.toBeTruthy(); - expect(wrapper.queryByText('On custom action intervals')).not.toBeTruthy(); + await userEvent.click(wrapper.getByTestId('notifyWhenSelect')); + expect(wrapper.queryByText('On status changes')).not.toBeTruthy(); + expect(wrapper.queryByText('On check intervals')).not.toBeTruthy(); + expect(wrapper.queryByText('On custom action intervals')).not.toBeTruthy(); - expect(wrapper.getAllByText('Per rule run')).toBeTruthy(); - expect(wrapper.queryByText('Custom frequency')).not.toBeTruthy(); + expect(wrapper.getAllByText('Per rule run')).toBeTruthy(); + expect(wrapper.queryByText('Custom frequency')).not.toBeTruthy(); - expect(wrapper.queryByTestId('onActionGroupChange')).not.toBeTruthy(); - expect(wrapper.getByTestId('onActiveAlert')).toBeTruthy(); - expect(wrapper.queryByTestId('onThrottleInterval')).not.toBeTruthy(); - }); + expect(wrapper.queryByTestId('onActionGroupChange')).not.toBeTruthy(); + expect(wrapper.getByTestId('onActiveAlert')).toBeTruthy(); + expect(wrapper.queryByTestId('onThrottleInterval')).not.toBeTruthy(); }); }); }); diff --git a/x-pack/solutions/observability/plugins/apm/public/components/app/settings/custom_link/create_edit_custom_link_flyout/link_preview.test.tsx b/x-pack/solutions/observability/plugins/apm/public/components/app/settings/custom_link/create_edit_custom_link_flyout/link_preview.test.tsx index 90a3d010a2baa..9b7e42742fe4f 100644 --- a/x-pack/solutions/observability/plugins/apm/public/components/app/settings/custom_link/create_edit_custom_link_flyout/link_preview.test.tsx +++ b/x-pack/solutions/observability/plugins/apm/public/components/app/settings/custom_link/create_edit_custom_link_flyout/link_preview.test.tsx @@ -6,7 +6,7 @@ */ import { composeStories } from '@storybook/react'; -import { render, getNodeText, getByTestId, act, waitFor } from '@testing-library/react'; +import { render, getNodeText, getByTestId, waitFor } from '@testing-library/react'; import React from 'react'; import * as stories from './link_preview.stories'; @@ -19,40 +19,34 @@ describe('LinkPreview', () => { getNodeText(getByTestId(container, id)); it('shows label and url default values', () => { - act(() => { - const { container } = render(); - expect(getElementValue(container, 'preview-label')).toEqual('Elastic.co'); - expect(getElementValue(container, 'preview-url')).toEqual('https://www.elastic.co'); - }); + const { container } = render(); + expect(getElementValue(container, 'preview-label')).toEqual('Elastic.co'); + expect(getElementValue(container, 'preview-url')).toEqual('https://www.elastic.co'); }); it('shows label and url values', () => { - act(() => { - const { container } = render( - - ); - expect(getElementValue(container, 'preview-label')).toEqual('foo'); - expect( - removeExternalLinkText((getByTestId(container, 'preview-link') as HTMLAnchorElement).text) - ).toContain('https://baz.co'); - }); + const { container } = render( + + ); + expect(getElementValue(container, 'preview-label')).toEqual('foo'); + expect( + removeExternalLinkText((getByTestId(container, 'preview-link') as HTMLAnchorElement).text) + ).toContain('https://baz.co'); }); it("shows warning when couldn't replace context variables", () => { - act(() => { - const { container } = render( - - ); - expect(getElementValue(container, 'preview-label')).toEqual('foo'); - expect( - removeExternalLinkText((getByTestId(container, 'preview-link') as HTMLAnchorElement).text) - ).toContain('https://baz.co?service.name={{invalid}'); - expect(getByTestId(container, 'preview-warning')).toBeInTheDocument(); - }); + const { container } = render( + + ); + expect(getElementValue(container, 'preview-label')).toEqual('foo'); + expect( + removeExternalLinkText((getByTestId(container, 'preview-link') as HTMLAnchorElement).text) + ).toContain('https://baz.co?service.name={{invalid}'); + expect(getByTestId(container, 'preview-warning')).toBeInTheDocument(); }); it('replaces url with transaction id', async () => { diff --git a/x-pack/solutions/observability/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall_container.test.tsx b/x-pack/solutions/observability/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall_container.test.tsx index ea2fd47163f6c..b9539a63b8878 100644 --- a/x-pack/solutions/observability/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall_container.test.tsx +++ b/x-pack/solutions/observability/plugins/apm/public/components/app/transaction_details/waterfall_with_summary/waterfall_container/waterfall_container.test.tsx @@ -8,6 +8,7 @@ import { composeStories } from '@storybook/react'; import { waitFor } from '@testing-library/react'; import React from 'react'; +import { userEvent } from '@testing-library/user-event'; import { disableConsoleWarning, renderWithTheme } from '../../../../../utils/test_helpers'; import * as stories from './waterfall_container.stories'; @@ -30,7 +31,7 @@ describe('WaterfallContainer', () => { const parentItem = buttons[1]; const childItem = buttons[2]; - parentItem.click(); + await userEvent.click(parentItem); expect(parentItem).toHaveAttribute('aria-expanded', 'false'); expect(childItem).toHaveAttribute('aria-expanded', 'true'); diff --git a/x-pack/solutions/observability/plugins/apm/public/components/shared/environment_select/index.test.tsx b/x-pack/solutions/observability/plugins/apm/public/components/shared/environment_select/index.test.tsx index 69753e39c3d47..5e02fd95a611c 100644 --- a/x-pack/solutions/observability/plugins/apm/public/components/shared/environment_select/index.test.tsx +++ b/x-pack/solutions/observability/plugins/apm/public/components/shared/environment_select/index.test.tsx @@ -63,7 +63,10 @@ describe('EnvironmentSelect', () => { }); it('Should not call onSearchChange if item is already listed', async () => { - const { getByRole } = render(); + const { getByRole } = render(, { + // TODO: fails with concurrent mode + legacyRoot: true, + }); const combobox = getByRole('combobox') as HTMLInputElement; expect(mockOnSearchChange.mock.calls.length).toBe(0); diff --git a/x-pack/solutions/observability/plugins/apm/public/hooks/use_fetcher.integration.test.tsx b/x-pack/solutions/observability/plugins/apm/public/hooks/use_fetcher.integration.test.tsx index 6512bfe5768f7..51f6219b60459 100644 --- a/x-pack/solutions/observability/plugins/apm/public/hooks/use_fetcher.integration.test.tsx +++ b/x-pack/solutions/observability/plugins/apm/public/hooks/use_fetcher.integration.test.tsx @@ -41,6 +41,7 @@ describe('when simulating race condition', () => { const { rerender } = render(, { wrapper, + legacyRoot: true, }); rerender(); diff --git a/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/exploratory_view.test.tsx b/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/exploratory_view.test.tsx index e8b01b10316c3..4e5f6857fe200 100644 --- a/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/exploratory_view.test.tsx +++ b/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/exploratory_view.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { render, mockAppDataView } from './rtl_helpers'; import { ExploratoryView } from './exploratory_view'; import * as obsvDataViews from '../../../utils/observability_data_views/observability_data_views'; @@ -87,7 +88,7 @@ describe('ExploratoryView', () => { const toggleButton = await screen.findByText('Hide chart'); expect(toggleButton).toBeInTheDocument(); - toggleButton.click(); + await userEvent.click(toggleButton); expect(toggleButton.textContent).toBe('Show chart'); expect(screen.queryByText('Refresh')).toBeNull(); diff --git a/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/columns/filter_value_btn.test.tsx b/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/columns/filter_value_btn.test.tsx index 814f63bc4224d..3eeb76e8de804 100644 --- a/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/columns/filter_value_btn.test.tsx +++ b/x-pack/solutions/observability/plugins/exploratory_view/public/components/shared/exploratory_view/series_editor/columns/filter_value_btn.test.tsx @@ -192,7 +192,9 @@ describe('FilterValueButton', function () { allSelectedValues={['Chrome', 'Firefox']} nestedField={USER_AGENT_VERSION} series={mockUxSeries} - /> + />, + // TODO: fails with concurrent mode due to `.toHaveBeenCalledTimes(5);` + { renderOptions: { legacyRoot: true } } ); await waitFor(() => { diff --git a/x-pack/solutions/observability/plugins/observability/public/pages/alert_details/alert_details.test.tsx b/x-pack/solutions/observability/plugins/observability/public/pages/alert_details/alert_details.test.tsx index 17b13cc6f140f..6ddf54555fd55 100644 --- a/x-pack/solutions/observability/plugins/observability/public/pages/alert_details/alert_details.test.tsx +++ b/x-pack/solutions/observability/plugins/observability/public/pages/alert_details/alert_details.test.tsx @@ -14,6 +14,7 @@ import { useBreadcrumbs, TagsList } from '@kbn/observability-shared-plugin/publi import { RuleTypeModel, ValidationResult } from '@kbn/triggers-actions-ui-plugin/public'; import { ruleTypeRegistryMock } from '@kbn/triggers-actions-ui-plugin/public/application/rule_type_registry.mock'; import { waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { Chance } from 'chance'; import React, { Fragment } from 'react'; import { useHistory, useLocation, useParams } from 'react-router-dom'; @@ -189,7 +190,7 @@ describe('Alert details', () => { expect(alertDetails.queryByTestId('alertDetailsTabbedContent')?.textContent).toContain( 'Metadata' ); - alertDetails.getByText('Metadata').click(); + await userEvent.click(alertDetails.getByText('Metadata')); expect(alertDetails.queryByTestId('metadataTabPanel')).toBeTruthy(); expect(alertDetails.queryByTestId('metadataTabPanel')?.textContent).toContain( 'kibana.alert.status' diff --git a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/public/functions/visualize_esql.test.tsx b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/public/functions/visualize_esql.test.tsx index 4a138aa8e427b..84ef69e44a25f 100644 --- a/x-pack/solutions/observability/plugins/observability_ai_assistant_app/public/functions/visualize_esql.test.tsx +++ b/x-pack/solutions/observability/plugins/observability_ai_assistant_app/public/functions/visualize_esql.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ import React from 'react'; -import { render, screen, waitFor, act } from '@testing-library/react'; +import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import type { DatatableColumn } from '@kbn/expressions-plugin/common'; import type { LensPublicStart } from '@kbn/lens-plugin/public'; @@ -180,11 +180,9 @@ describe('VisualizeESQL', () => { renderComponent({}, lensService); - await act(async () => { - await userEvent.click( - await screen.findByTestId('observabilityAiAssistantLensESQLDisplayTableButton') - ); - }); + await userEvent.click( + await screen.findByTestId('observabilityAiAssistantLensESQLDisplayTableButton') + ); expect(await screen.findByTestId('observabilityAiAssistantESQLDataGrid')).toBeInTheDocument(); }); diff --git a/x-pack/solutions/observability/plugins/slo/public/pages/slos/slos.test.tsx b/x-pack/solutions/observability/plugins/slo/public/pages/slos/slos.test.tsx index 830119bef8f79..7c5b27d9e0d39 100644 --- a/x-pack/solutions/observability/plugins/slo/public/pages/slos/slos.test.tsx +++ b/x-pack/solutions/observability/plugins/slo/public/pages/slos/slos.test.tsx @@ -324,7 +324,9 @@ describe('SLOs Page', () => { expect(button).toBeTruthy(); - button.click(); + act(() => { + button.click(); + }); expect(screen.getByTestId('add-rule-flyout')).toBeInTheDocument(); }); @@ -377,7 +379,9 @@ describe('SLOs Page', () => { expect(button).toBeTruthy(); - button.click(); + act(() => { + button.click(); + }); screen.getByTestId('observabilitySolutionSloDeleteModalConfirmButton').click(); diff --git a/x-pack/solutions/search/plugins/search_inference_endpoints/public/components/all_inference_endpoints/tabular_page.test.tsx b/x-pack/solutions/search/plugins/search_inference_endpoints/public/components/all_inference_endpoints/tabular_page.test.tsx index 85e8fe656d1c3..395b60c03ee45 100644 --- a/x-pack/solutions/search/plugins/search_inference_endpoints/public/components/all_inference_endpoints/tabular_page.test.tsx +++ b/x-pack/solutions/search/plugins/search_inference_endpoints/public/components/all_inference_endpoints/tabular_page.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { screen } from '@testing-library/react'; +import { act, screen } from '@testing-library/react'; import { render } from '@testing-library/react'; import { TabularPage } from './tabular_page'; import { InferenceAPIConfigResponse } from '@kbn/ml-trained-models-utils'; @@ -139,7 +139,9 @@ describe('When the tabular page is loaded', () => { it('should only disable delete action for preconfigured endpoints', () => { render(); - screen.getAllByTestId('euiCollapsedItemActionsButton')[0].click(); + act(() => { + screen.getAllByTestId('euiCollapsedItemActionsButton')[0].click(); + }); const deleteAction = screen.getByTestId(/inferenceUIDeleteAction/); @@ -149,7 +151,9 @@ describe('When the tabular page is loaded', () => { it('should not disable delete action for other endpoints', () => { render(); - screen.getAllByTestId('euiCollapsedItemActionsButton')[4].click(); + act(() => { + screen.getAllByTestId('euiCollapsedItemActionsButton')[4].click(); + }); const deleteAction = screen.getByTestId(/inferenceUIDeleteAction/); diff --git a/x-pack/solutions/security/packages/ecs-data-quality-dashboard/impl/data_quality_panel/data_quality_details/indices_details/index.test.tsx b/x-pack/solutions/security/packages/ecs-data-quality-dashboard/impl/data_quality_panel/data_quality_details/indices_details/index.test.tsx index 44f51a50cc027..ce62a1129efce 100644 --- a/x-pack/solutions/security/packages/ecs-data-quality-dashboard/impl/data_quality_panel/data_quality_details/indices_details/index.test.tsx +++ b/x-pack/solutions/security/packages/ecs-data-quality-dashboard/impl/data_quality_panel/data_quality_details/indices_details/index.test.tsx @@ -107,7 +107,7 @@ describe('IndicesDetails', () => { describe('when the tour is dismissed', () => { test('it hides the tour and persists in localStorage', async () => { - const wrapper = screen.getByTestId('historicalResultsTourPanel'); + const wrapper = await screen.findByTestId('historicalResultsTourPanel'); const button = within(wrapper).getByText('Close'); await userEvent.click(button); diff --git a/x-pack/solutions/security/packages/ecs-data-quality-dashboard/impl/data_quality_panel/data_quality_details/indices_details/pattern/index_check_flyout/historical_results/index.test.tsx b/x-pack/solutions/security/packages/ecs-data-quality-dashboard/impl/data_quality_panel/data_quality_details/indices_details/pattern/index_check_flyout/historical_results/index.test.tsx index 9a74d5ffaa3f7..b085c0997ebd6 100644 --- a/x-pack/solutions/security/packages/ecs-data-quality-dashboard/impl/data_quality_panel/data_quality_details/indices_details/pattern/index_check_flyout/historical_results/index.test.tsx +++ b/x-pack/solutions/security/packages/ecs-data-quality-dashboard/impl/data_quality_panel/data_quality_details/indices_details/pattern/index_check_flyout/historical_results/index.test.tsx @@ -182,11 +182,9 @@ describe('HistoricalResults', () => { await userEvent.click(dateQuickSelect); }); - await act(async () => { - const monthToDateButton = screen.getByTestId('superDatePickerCommonlyUsed_Month_to date'); + const monthToDateButton = screen.getByTestId('superDatePickerCommonlyUsed_Month_to date'); - await userEvent.click(monthToDateButton); - }); + await userEvent.click(monthToDateButton); const fetchQueryOpts = { abortController: expect.any(AbortController), @@ -391,11 +389,9 @@ describe('HistoricalResults', () => { const wrapper = screen.getByTestId('historicalResultsPagination'); - await act(() => - userEvent.click(within(wrapper).getByTestId('tablePaginationPopoverButton')) - ); + await userEvent.click(within(wrapper).getByTestId('tablePaginationPopoverButton')); - await act(() => userEvent.click(screen.getByTestId('tablePagination-25-rows'))); + await userEvent.click(screen.getByTestId('tablePagination-25-rows')); const fetchQueryOpts = { abortController: expect.any(AbortController), diff --git a/x-pack/solutions/security/packages/expandable-flyout/src/components/settings_menu.test.tsx b/x-pack/solutions/security/packages/expandable-flyout/src/components/settings_menu.test.tsx index c9452172d86c3..3ab3e40ea61c0 100644 --- a/x-pack/solutions/security/packages/expandable-flyout/src/components/settings_menu.test.tsx +++ b/x-pack/solutions/security/packages/expandable-flyout/src/components/settings_menu.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { render } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { SettingsMenu } from './settings_menu'; import { @@ -39,7 +40,7 @@ describe('SettingsMenu', () => { }); describe('push vs overlay', () => { - it('should render the flyout type button group', () => { + it('should render the flyout type button group', async () => { const flyoutCustomProps = { hideSettings: false, pushVsOverlay: { @@ -54,7 +55,7 @@ describe('SettingsMenu', () => { ); - getByTestId(SETTINGS_MENU_BUTTON_TEST_ID).click(); + await userEvent.click(getByTestId(SETTINGS_MENU_BUTTON_TEST_ID)); expect(getByTestId(SETTINGS_MENU_FLYOUT_TYPE_TITLE_TEST_ID)).toBeInTheDocument(); expect( @@ -63,7 +64,7 @@ describe('SettingsMenu', () => { expect(getByTestId(SETTINGS_MENU_FLYOUT_TYPE_BUTTON_GROUP_TEST_ID)).toBeInTheDocument(); }); - it('should have the type selected if option is enabled', () => { + it('should have the type selected if option is enabled', async () => { const state = { panels: initialPanelsState, ui: { @@ -85,7 +86,7 @@ describe('SettingsMenu', () => { ); - getByTestId(SETTINGS_MENU_BUTTON_TEST_ID).click(); + await userEvent.click(getByTestId(SETTINGS_MENU_BUTTON_TEST_ID)); expect(getByTestId(SETTINGS_MENU_FLYOUT_TYPE_BUTTON_GROUP_PUSH_TEST_ID)).toHaveClass( 'euiButtonGroupButton-isSelected' @@ -107,7 +108,9 @@ describe('SettingsMenu', () => { const { getByTestId } = render( - + , + // fails with concurrent mode and userEvent.click + { legacyRoot: true } ); expect(localStorage.getItem(EXPANDABLE_FLYOUT_LOCAL_STORAGE)).toEqual(null); @@ -126,7 +129,7 @@ describe('SettingsMenu', () => { ); }); - it('should render the the flyout type button group disabled', () => { + it('should render the the flyout type button group disabled', async () => { const flyoutCustomProps = { hideSettings: false, pushVsOverlay: { @@ -138,7 +141,9 @@ describe('SettingsMenu', () => { const { getByTestId } = render( - + , + // fails with concurrent mode and userEvent.click + { legacyRoot: true } ); expect(localStorage.getItem(EXPANDABLE_FLYOUT_LOCAL_STORAGE)).toEqual(null); @@ -162,7 +167,7 @@ describe('SettingsMenu', () => { expect(localStorage.getItem(EXPANDABLE_FLYOUT_LOCAL_STORAGE)).toEqual(null); }); - it('should not render the information icon if the tooltip is empty', () => { + it('should not render the information icon if the tooltip is empty', async () => { const flyoutCustomProps = { hideSettings: false, pushVsOverlay: { @@ -177,7 +182,7 @@ describe('SettingsMenu', () => { ); - getByTestId(SETTINGS_MENU_BUTTON_TEST_ID).click(); + await userEvent.click(getByTestId(SETTINGS_MENU_BUTTON_TEST_ID)); expect( queryByTestId(SETTINGS_MENU_FLYOUT_TYPE_INFORMATION_ICON_TEST_ID) @@ -186,7 +191,7 @@ describe('SettingsMenu', () => { }); describe('resize', () => { - it('should render the flyout resize button', () => { + it('should render the flyout resize button', async () => { const flyoutCustomProps = { hideSettings: false, resize: { @@ -200,7 +205,7 @@ describe('SettingsMenu', () => { ); - getByTestId(SETTINGS_MENU_BUTTON_TEST_ID).click(); + await userEvent.click(getByTestId(SETTINGS_MENU_BUTTON_TEST_ID)); expect(getByTestId(SETTINGS_MENU_FLYOUT_RESIZE_TITLE_TEST_ID)).toBeInTheDocument(); expect( @@ -209,7 +214,7 @@ describe('SettingsMenu', () => { expect(getByTestId(SETTINGS_MENU_FLYOUT_RESIZE_BUTTON_TEST_ID)).toBeInTheDocument(); }); - it('should reset correctly when clicked', () => { + it('should reset correctly when clicked', async () => { const flyoutCustomProps = { hideSettings: false, resize: { @@ -233,8 +238,8 @@ describe('SettingsMenu', () => { ); - getByTestId(SETTINGS_MENU_BUTTON_TEST_ID).click(); - getByTestId(SETTINGS_MENU_FLYOUT_RESIZE_BUTTON_TEST_ID).click(); + await userEvent.click(getByTestId(SETTINGS_MENU_BUTTON_TEST_ID)); + await userEvent.click(getByTestId(SETTINGS_MENU_FLYOUT_RESIZE_BUTTON_TEST_ID)); const expandableFlyout = localStorage.getItem(EXPANDABLE_FLYOUT_LOCAL_STORAGE); expect(expandableFlyout).not.toBe(null); @@ -244,7 +249,7 @@ describe('SettingsMenu', () => { expect(expandableFlyout).not.toHaveProperty(USER_SECTION_WIDTHS_LOCAL_STORAGE); }); - it('should render the the flyout resize button disabled', () => { + it('should render the the flyout resize button disabled', async () => { const flyoutCustomProps = { hideSettings: false, resize: { @@ -259,12 +264,12 @@ describe('SettingsMenu', () => { ); - getByTestId(SETTINGS_MENU_BUTTON_TEST_ID).click(); + await userEvent.click(getByTestId(SETTINGS_MENU_BUTTON_TEST_ID)); expect(getByTestId(SETTINGS_MENU_FLYOUT_RESIZE_BUTTON_TEST_ID)).toHaveAttribute('disabled'); expect(getByTestId(SETTINGS_MENU_FLYOUT_RESIZE_INFORMATION_ICON_TEST_ID)).toBeInTheDocument(); }); - it('should not render the information icon if the tooltip is empty', () => { + it('should not render the information icon if the tooltip is empty', async () => { const flyoutCustomProps = { hideSettings: false, resize: { @@ -279,7 +284,7 @@ describe('SettingsMenu', () => { ); - getByTestId(SETTINGS_MENU_BUTTON_TEST_ID).click(); + await userEvent.click(getByTestId(SETTINGS_MENU_BUTTON_TEST_ID)); expect( queryByTestId(SETTINGS_MENU_FLYOUT_RESIZE_INFORMATION_ICON_TEST_ID) ).not.toBeInTheDocument(); diff --git a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.stories.test.tsx b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.stories.test.tsx index 474faf357a1d6..c144cb50a133a 100644 --- a/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.stories.test.tsx +++ b/x-pack/solutions/security/packages/kbn-cloud-security-posture/graph/src/components/graph_investigation/graph_investigation.stories.test.tsx @@ -51,7 +51,11 @@ const renderStory = (args: Partial = {}) => { return render( - + , + { + // TODO: Fails in concurrent mode + legacyRoot: true, + } ); }; diff --git a/x-pack/solutions/security/packages/side-nav/src/solution_side_nav.test.tsx b/x-pack/solutions/security/packages/side-nav/src/solution_side_nav.test.tsx index b5db8e66f10dd..356e8deadee49 100644 --- a/x-pack/solutions/security/packages/side-nav/src/solution_side_nav.test.tsx +++ b/x-pack/solutions/security/packages/side-nav/src/solution_side_nav.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { render } from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; import { SolutionSideNav, type SolutionSideNavProps } from './solution_side_nav'; import type { SolutionSideNavItem } from './types'; import { METRIC_TYPE } from '@kbn/analytics'; @@ -62,7 +63,7 @@ describe('SolutionSideNav', () => { ); }); - it('should call onClick callback if link clicked', () => { + it('should call onClick callback if link clicked', async () => { const mockOnClick = jest.fn((ev) => { ev.preventDefault(); }); @@ -76,11 +77,11 @@ describe('SolutionSideNav', () => { }, ]; const result = renderNav({ items }); - result.getByTestId(`solutionSideNavItemLink-${'exploreLanding'}`).click(); + await userEvent.click(result.getByTestId(`solutionSideNavItemLink-${'exploreLanding'}`)); expect(mockOnClick).toHaveBeenCalled(); }); - it('should send telemetry if link clicked', () => { + it('should send telemetry if link clicked', async () => { const items = [ ...mockItems, { @@ -90,7 +91,7 @@ describe('SolutionSideNav', () => { }, ]; const result = renderNav({ items }); - result.getByTestId(`solutionSideNavItemLink-${'exploreLanding'}`).click(); + await userEvent.click(result.getByTestId(`solutionSideNavItemLink-${'exploreLanding'}`)); expect(mockTrack).toHaveBeenCalledWith( METRIC_TYPE.CLICK, `${TELEMETRY_EVENT.NAVIGATION}${'exploreLanding'}` @@ -107,32 +108,32 @@ describe('SolutionSideNav', () => { expect(result.queryByTestId(`solutionSideNavItemButton-${'alerts'}`)).not.toBeInTheDocument(); }); - it('should render the panel when button is clicked', () => { + it('should render the panel when button is clicked', async () => { const result = renderNav(); expect(result.queryByTestId('solutionSideNavPanel')).not.toBeInTheDocument(); - result.getByTestId(`solutionSideNavItemButton-${'dashboardsLanding'}`).click(); + await userEvent.click(result.getByTestId(`solutionSideNavItemButton-${'dashboardsLanding'}`)); expect(result.getByTestId('solutionSideNavPanel')).toBeInTheDocument(); expect(result.getByText('Overview')).toBeInTheDocument(); }); - it('should telemetry when button is clicked', () => { + it('should telemetry when button is clicked', async () => { const result = renderNav(); expect(result.queryByTestId('solutionSideNavPanel')).not.toBeInTheDocument(); - result.getByTestId(`solutionSideNavItemButton-${'dashboardsLanding'}`).click(); + await userEvent.click(result.getByTestId(`solutionSideNavItemButton-${'dashboardsLanding'}`)); expect(mockTrack).toHaveBeenCalledWith( METRIC_TYPE.CLICK, `${TELEMETRY_EVENT.PANEL_NAVIGATION_TOGGLE}${'dashboardsLanding'}` ); }); - it('should close the panel when the same button is clicked', () => { + it('should close the panel when the same button is clicked', async () => { const result = renderNav(); - result.getByTestId(`solutionSideNavItemButton-${'dashboardsLanding'}`).click(); + await userEvent.click(result.getByTestId(`solutionSideNavItemButton-${'dashboardsLanding'}`)); expect(result.getByTestId('solutionSideNavPanel')).toBeInTheDocument(); - result.getByTestId(`solutionSideNavItemButton-${'dashboardsLanding'}`).click(); + await userEvent.click(result.getByTestId(`solutionSideNavItemButton-${'dashboardsLanding'}`)); // add check at the end of the event loop to ensure the panel is removed setTimeout(() => { @@ -140,7 +141,7 @@ describe('SolutionSideNav', () => { }); }); - it('should open other panel when other button is clicked while open', () => { + it('should open other panel when other button is clicked while open', async () => { const items = [ ...mockItems, { @@ -159,11 +160,11 @@ describe('SolutionSideNav', () => { ]; const result = renderNav({ items }); - result.getByTestId(`solutionSideNavItemButton-${'dashboardsLanding'}`).click(); + await userEvent.click(result.getByTestId(`solutionSideNavItemButton-${'dashboardsLanding'}`)); expect(result.getByTestId('solutionSideNavPanel')).toBeInTheDocument(); expect(result.getByText('Overview')).toBeInTheDocument(); - result.getByTestId(`solutionSideNavItemButton-${'exploreLanding'}`).click(); + await userEvent.click(result.getByTestId(`solutionSideNavItemButton-${'exploreLanding'}`)); expect(result.queryByTestId('solutionSideNavPanel')).toBeInTheDocument(); expect(result.getByText('Users')).toBeInTheDocument(); }); diff --git a/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/compliance_dashboard/compliance_dashboard.test.tsx b/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/compliance_dashboard/compliance_dashboard.test.tsx index 11d7a71118eae..1df1f318daf7a 100644 --- a/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/compliance_dashboard/compliance_dashboard.test.tsx +++ b/x-pack/solutions/security/plugins/cloud_security_posture/public/pages/compliance_dashboard/compliance_dashboard.test.tsx @@ -35,6 +35,7 @@ import { import { ComplianceDashboardDataV2 } from '../../../common/types_old'; import { cloudPosturePages } from '../../common/navigation/constants'; import { MemoryRouter } from 'react-router-dom'; +import userEvent from '@testing-library/user-event'; jest.mock('@kbn/cloud-security-posture/src/hooks/use_csp_setup_status_api'); jest.mock('../../common/api/use_stats_api'); @@ -619,7 +620,7 @@ describe('', () => { }); }); - it('Show CSPM installation prompt if CSPM is not installed and KSPM is installed ,NO AGENT', () => { + it('Show CSPM installation prompt if CSPM is not installed and KSPM is installed ,NO AGENT', async () => { (useCspSetupStatusApi as jest.Mock).mockImplementation(() => createReactQueryResponse({ status: 'success', @@ -647,7 +648,7 @@ describe('', () => { renderComplianceDashboardPage(cloudPosturePages.kspm_dashboard.path); - screen.getByTestId(CLOUD_DASHBOARD_TAB).click(); + await userEvent.click(screen.getByTestId(CLOUD_DASHBOARD_TAB)); expectIdsInDoc({ be: [CSPM_INTEGRATION_NOT_INSTALLED_TEST_SUBJECT], @@ -661,7 +662,7 @@ describe('', () => { }); }); - it('Show KSPM installation prompt if KSPM is not installed and CSPM is installed , NO AGENT', () => { + it('Show KSPM installation prompt if KSPM is not installed and CSPM is installed , NO AGENT', async () => { (useCspSetupStatusApi as jest.Mock).mockImplementation(() => createReactQueryResponse({ status: 'success', @@ -689,7 +690,7 @@ describe('', () => { renderComplianceDashboardPage(); - screen.getByTestId(KUBERNETES_DASHBOARD_TAB).click(); + await userEvent.click(screen.getByTestId(KUBERNETES_DASHBOARD_TAB)); expectIdsInDoc({ be: [KSPM_INTEGRATION_NOT_INSTALLED_TEST_SUBJECT], diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/components/assignees/assignees_apply_panel.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/common/components/assignees/assignees_apply_panel.test.tsx index d9cec32f5ce1f..f3d84fe095988 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/components/assignees/assignees_apply_panel.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/common/components/assignees/assignees_apply_panel.test.tsx @@ -16,6 +16,7 @@ import { useBulkGetUserProfiles } from '../user_profiles/use_bulk_get_user_profi import { useSuggestUsers } from '../user_profiles/use_suggest_users'; import { TestProviders } from '../../mock'; import { mockUserProfiles } from './mocks'; +import userEvent from '@testing-library/user-event'; jest.mock('../user_profiles/use_get_current_user_profile'); jest.mock('../user_profiles/use_bulk_get_user_profiles'); @@ -66,7 +67,7 @@ describe('', () => { expect(getByTestId(ASSIGNEES_APPLY_BUTTON_TEST_ID)).toBeDisabled(); }); - it('should call `onApply` callback on apply button click', () => { + it('should call `onApply` callback on apply button click', async () => { const mockedOnApply = jest.fn(); const { getByText, getByTestId } = renderAssigneesApplyPanel({ @@ -75,9 +76,9 @@ describe('', () => { }); expect(getByTestId(ASSIGNEES_APPLY_BUTTON_TEST_ID)).toBeDisabled(); - getByText(mockUserProfiles[1].user.full_name).click(); + await userEvent.click(getByText(mockUserProfiles[1].user.full_name)); expect(getByTestId(ASSIGNEES_APPLY_BUTTON_TEST_ID)).not.toBeDisabled(); - getByTestId(ASSIGNEES_APPLY_BUTTON_TEST_ID).click(); + await userEvent.click(getByTestId(ASSIGNEES_APPLY_BUTTON_TEST_ID)); expect(mockedOnApply).toHaveBeenCalledWith({ add: ['user-id-2'], diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/components/assignees/assignees_selectable.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/common/components/assignees/assignees_selectable.test.tsx index 56115920ee5c3..5385f00b124b2 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/components/assignees/assignees_selectable.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/common/components/assignees/assignees_selectable.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { render } from '@testing-library/react'; +import { userEvent } from '@testing-library/user-event'; import { AssigneesSelectable } from './assignees_selectable'; @@ -81,7 +82,7 @@ describe('', () => { expect(assigneesList).toHaveTextContent(i18n.ASSIGNEES_NO_ASSIGNEES); }); - it('should call `onSelectionChange` on user selection', () => { + it('should call `onSelectionChange` on user selection', async () => { (useBulkGetUserProfiles as jest.Mock).mockReturnValue({ isLoading: false, data: [], @@ -93,12 +94,12 @@ describe('', () => { onSelectionChange: onSelectionChangeMock, }); - getByText('User 1').click(); - getByText('User 2').click(); - getByText('User 3').click(); - getByText('User 3').click(); - getByText('User 2').click(); - getByText('User 1').click(); + await userEvent.click(getByText('User 1')); + await userEvent.click(getByText('User 2')); + await userEvent.click(getByText('User 3')); + await userEvent.click(getByText('User 3')); + await userEvent.click(getByText('User 2')); + await userEvent.click(getByText('User 1')); expect(onSelectionChangeMock).toHaveBeenCalledTimes(6); expect(onSelectionChangeMock.mock.calls).toEqual([ diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/components/events_tab/events_query_tab_body.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/common/components/events_tab/events_query_tab_body.test.tsx index a09d7e63c3d46..56667c8868b24 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/components/events_tab/events_query_tab_body.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/common/components/events_tab/events_query_tab_body.test.tsx @@ -18,6 +18,7 @@ import { mockHistory } from '../../mock/router'; import { DEFAULT_EVENTS_STACK_BY_VALUE } from './histogram_configurations'; import { useIsExperimentalFeatureEnabled } from '../../hooks/use_experimental_features'; import { useUserPrivileges } from '../user_privileges'; +import userEvent from '@testing-library/user-event'; jest.mock('../../hooks/use_experimental_features'); jest.mock('../user_privileges'); @@ -161,14 +162,14 @@ describe('EventsQueryTabBody', () => { ); }); - it('renders the matrix histogram stacked by alerts default value', () => { + it('renders the matrix histogram stacked by alerts default value', async () => { const result = render( ); - result.getByTestId('showExternalAlertsCheckbox').click(); + await userEvent.click(result.getByTestId('showExternalAlertsCheckbox')); expect(result.getByTestId('header-section-supplements').querySelector('select')?.value).toEqual( 'event.module' diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/components/filter_by_assignees_popover/filter_by_assignees_popover.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/common/components/filter_by_assignees_popover/filter_by_assignees_popover.test.tsx index 5e912e9e5c71d..86fd356255c53 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/components/filter_by_assignees_popover/filter_by_assignees_popover.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/common/components/filter_by_assignees_popover/filter_by_assignees_popover.test.tsx @@ -18,6 +18,7 @@ import { useSuggestUsers } from '../user_profiles/use_suggest_users'; import { useLicense } from '../../hooks/use_license'; import { useUpsellingMessage } from '../../hooks/use_upselling'; import { FILTER_BY_ASSIGNEES_BUTTON } from './test_ids'; +import userEvent from '@testing-library/user-event'; jest.mock('../user_profiles/use_get_current_user_profile'); jest.mock('../user_profiles/use_bulk_get_user_profiles'); @@ -85,17 +86,17 @@ describe('', () => { expect(queryByTestId('euiSelectableList')).not.toBeInTheDocument(); }); - it('should render opened popover component', () => { + it('should render opened popover component', async () => { const { getByTestId } = renderFilterByAssigneesPopover(); - getByTestId(FILTER_BY_ASSIGNEES_BUTTON).click(); + await userEvent.click(getByTestId(FILTER_BY_ASSIGNEES_BUTTON)); expect(getByTestId('euiSelectableList')).toBeInTheDocument(); }); - it('should render assignees', () => { + it('should render assignees', async () => { const { getByTestId } = renderFilterByAssigneesPopover(); - getByTestId(FILTER_BY_ASSIGNEES_BUTTON).click(); + await userEvent.click(getByTestId(FILTER_BY_ASSIGNEES_BUTTON)); const assigneesList = getByTestId('euiSelectableList'); expect(assigneesList).toHaveTextContent('User 1'); diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/components/guided_onboarding_tour/cases_tour_steps.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/common/components/guided_onboarding_tour/cases_tour_steps.test.tsx index 3cf8d696833b3..96a3ed5ba3b18 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/components/guided_onboarding_tour/cases_tour_steps.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/common/components/guided_onboarding_tour/cases_tour_steps.test.tsx @@ -10,6 +10,7 @@ import { render } from '@testing-library/react'; import { CasesTourSteps } from './cases_tour_steps'; import { AlertsCasesTourSteps } from './tour_config'; import { TestProviders } from '../../mock'; +import userEvent from '@testing-library/user-event'; jest.mock('./tour_step', () => ({ GuidedOnboardingTourStep: jest @@ -21,13 +22,17 @@ jest.mock('./tour_step', () => ({ describe('cases tour steps', () => { it('Mounts with AlertsCasesTourSteps.createCase step active', () => { - const { getByTestId, queryByTestId } = render(, { wrapper: TestProviders }); + const { getByTestId, queryByTestId } = render(, { + wrapper: TestProviders, + }); expect(getByTestId(`step-${AlertsCasesTourSteps.createCase}`)).toBeInTheDocument(); expect(queryByTestId(`step-${AlertsCasesTourSteps.submitCase}`)).not.toBeInTheDocument(); }); - it('On click next, AlertsCasesTourSteps.submitCase step active', () => { - const { getByTestId, queryByTestId } = render(, { wrapper: TestProviders }); - getByTestId(`step-${AlertsCasesTourSteps.createCase}`).click(); + it('On click next, AlertsCasesTourSteps.submitCase step active', async () => { + const { getByTestId, queryByTestId } = render(, { + wrapper: TestProviders, + }); + await userEvent.click(getByTestId(`step-${AlertsCasesTourSteps.createCase}`)); expect(getByTestId(`step-${AlertsCasesTourSteps.submitCase}`)).toBeInTheDocument(); expect(queryByTestId(`step-${AlertsCasesTourSteps.createCase}`)).not.toBeInTheDocument(); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/hooks/use_form_with_warnings/use_form_with_warnings.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/common/hooks/use_form_with_warnings/use_form_with_warnings.test.tsx index c9c9a939458e2..a079e9dfff4e5 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/hooks/use_form_with_warnings/use_form_with_warnings.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/common/hooks/use_form_with_warnings/use_form_with_warnings.test.tsx @@ -24,7 +24,7 @@ describe('useFormWithWarn', () => { it('is `true` when input is valid', async () => { render(); - typeText('someValue'); + await typeText('someValue'); await submitForm(); await waitFor(() => { @@ -35,7 +35,7 @@ describe('useFormWithWarn', () => { it('is `true` when input has warnings', async () => { render(); - typeText('warning'); + await typeText('warning'); await submitForm(); expect(screen.getByText('isValid: true')).toBeInTheDocument(); @@ -44,7 +44,7 @@ describe('useFormWithWarn', () => { it('is `false` when input has error', async () => { render(); - typeText('error'); + await typeText('error'); await submitForm(); expect(screen.getByText('isValid: false')).toBeInTheDocument(); @@ -53,7 +53,7 @@ describe('useFormWithWarn', () => { describe('isSubmitting', () => { it('toggles upon form submission', async () => { - render(); + render(, { legacyRoot: true }); expect(screen.getByText('isSubmitting: false')).toBeInTheDocument(); @@ -87,7 +87,7 @@ describe('useFormWithWarn', () => { const handleSubmit = jest.fn(); render(); - typeText('someValue'); + await typeText('someValue'); await submitForm(); @@ -105,7 +105,7 @@ describe('useFormWithWarn', () => { const handleSubmit = jest.fn(); render(); - typeText('warning'); + await typeText('warning'); await submitForm(); @@ -129,7 +129,7 @@ describe('useFormWithWarn', () => { const handleSubmit = jest.fn(); render(); - typeText('error'); + await typeText('error'); await submitForm(); @@ -153,7 +153,7 @@ describe('useFormWithWarn', () => { const handleSubmit = jest.fn(); render(); - typeText('error warning'); + await typeText('error warning'); await submitForm(); @@ -232,8 +232,8 @@ function submitForm(): Promise { }); } -function typeText(value: string): void { - act(() => { +async function typeText(value: string): Promise { + await act(() => { fireEvent.input(screen.getByRole('textbox'), { target: { value }, }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/test/eui/combobox.ts b/x-pack/solutions/security/plugins/security_solution/public/common/test/eui/combobox.ts index 6a3759d253c38..d00e6cd8b6d5f 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/test/eui/combobox.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/common/test/eui/combobox.ts @@ -7,8 +7,10 @@ import { act, fireEvent, waitFor, within } from '@testing-library/react'; -export function showEuiComboBoxOptions(comboBoxToggleButton: HTMLElement): Promise { - fireEvent.click(comboBoxToggleButton); +export async function showEuiComboBoxOptions(comboBoxToggleButton: HTMLElement): Promise { + await act(() => { + fireEvent.click(comboBoxToggleButton); + }); return waitFor(() => { const listWithOptionsElement = document.querySelector('[role="listbox"]'); @@ -30,14 +32,14 @@ type SelectEuiComboBoxOptionParameters = optionIndex?: undefined; }; -export function selectEuiComboBoxOption({ +export async function selectEuiComboBoxOption({ comboBoxToggleButton, optionIndex, optionText, }: SelectEuiComboBoxOptionParameters): Promise { - return act(async () => { - await showEuiComboBoxOptions(comboBoxToggleButton); + await showEuiComboBoxOptions(comboBoxToggleButton); + return act(async () => { const options = Array.from( document.querySelectorAll('[data-test-subj*="comboBoxOptionsList"] [role="option"]') ); diff --git a/x-pack/solutions/security/plugins/security_solution/public/common/test/eui/super_select.ts b/x-pack/solutions/security/plugins/security_solution/public/common/test/eui/super_select.ts index 207e8d2406dcc..fb01d68883499 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/common/test/eui/super_select.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/common/test/eui/super_select.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { act, fireEvent, waitFor } from '@testing-library/react'; +import { fireEvent, waitFor } from '@testing-library/react'; export function showEuiSuperSelectOptions(toggleButton: HTMLElement): Promise { fireEvent.click(toggleButton); @@ -30,33 +30,31 @@ type SelectEuiSuperSelectOptionParameters = optionIndex?: undefined; }; -export function selectEuiSuperSelectOption({ +export async function selectEuiSuperSelectOption({ toggleButton, optionIndex, optionText, }: SelectEuiSuperSelectOptionParameters): Promise { - return act(async () => { - await showEuiSuperSelectOptions(toggleButton); + await showEuiSuperSelectOptions(toggleButton); - const options = Array.from(document.querySelectorAll('[role="listbox"] [role="option"]')); + const options = Array.from(document.querySelectorAll('[role="listbox"] [role="option"]')); - if (typeof optionText === 'string') { - const lowerCaseOptionText = optionText.toLocaleLowerCase(); - const optionToSelect = options.find( - (option) => option.textContent?.toLowerCase() === lowerCaseOptionText - ); + if (typeof optionText === 'string') { + const lowerCaseOptionText = optionText.toLocaleLowerCase(); + const optionToSelect = options.find( + (option) => option.textContent?.toLowerCase() === lowerCaseOptionText + ); - if (optionToSelect) { - fireEvent.click(optionToSelect); - } else { - throw new Error( - `Could not find option with text "${optionText}". Available options: ${options - .map((option) => option.textContent) - .join(', ')}` - ); - } + if (optionToSelect) { + fireEvent.click(optionToSelect); } else { - fireEvent.click(options[optionIndex]); + throw new Error( + `Could not find option with text "${optionText}". Available options: ${options + .map((option) => option.textContent) + .join(', ')}` + ); } - }); + } else { + fireEvent.click(options[optionIndex]); + } } diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/required_fields/required_fields.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/required_fields/required_fields.test.tsx index 2812c147d9c2d..5dd6a651a9458 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/required_fields/required_fields.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_creation/components/required_fields/required_fields.test.tsx @@ -585,8 +585,10 @@ export function addRequiredFieldRow(): Promise { }); } -function showEuiComboBoxOptions(comboBoxToggleButton: HTMLElement): Promise { - fireEvent.click(comboBoxToggleButton); +async function showEuiComboBoxOptions(comboBoxToggleButton: HTMLElement): Promise { + await act(async () => { + fireEvent.click(comboBoxToggleButton); + }); return waitFor(() => { const listWithOptionsElement = document.querySelector('[role="listbox"]'); @@ -608,14 +610,14 @@ type SelectEuiComboBoxOptionParameters = optionIndex?: undefined; }; -function selectEuiComboBoxOption({ +async function selectEuiComboBoxOption({ comboBoxToggleButton, optionIndex, optionText, }: SelectEuiComboBoxOptionParameters): Promise { - return act(async () => { - await showEuiComboBoxOptions(comboBoxToggleButton); + await showEuiComboBoxOptions(comboBoxToggleButton); + return act(async () => { const options = Array.from( document.querySelectorAll('[data-test-subj*="comboBoxOptionsList"] [role="option"]') ); @@ -646,16 +648,16 @@ function selectFirstEuiComboBoxOption({ return selectEuiComboBoxOption({ comboBoxToggleButton, optionIndex: 0 }); } -function typeInCustomComboBoxOption({ +async function typeInCustomComboBoxOption({ comboBoxToggleButton, optionText, }: { comboBoxToggleButton: HTMLElement; optionText: string; }) { - return act(async () => { - await showEuiComboBoxOptions(comboBoxToggleButton); + await showEuiComboBoxOptions(comboBoxToggleButton); + return act(async () => { fireEvent.change(document.activeElement as HTMLInputElement, { target: { value: optionText } }); fireEvent.keyDown(document.activeElement as HTMLInputElement, { key: 'Enter' }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/logic/use_dissasociate_exception_list.test.ts b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/logic/use_dissasociate_exception_list.test.ts index 37acd41f98229..386146bdc1e6c 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/logic/use_dissasociate_exception_list.test.ts +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management/logic/use_dissasociate_exception_list.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { act, waitFor, renderHook } from '@testing-library/react'; +import { waitFor, renderHook } from '@testing-library/react'; import { coreMock } from '@kbn/core/public/mocks'; @@ -28,17 +28,15 @@ describe('useDisassociateExceptionList', () => { }); test('initializes hook', async () => { - await act(async () => { - const { result } = renderHook(() => - useDisassociateExceptionList({ - http: mockKibanaHttpService, - ruleRuleId: 'rule_id', - onError, - onSuccess, - }) - ); - - await waitFor(() => expect(result.current).toEqual([false, null])); - }); + const { result } = renderHook(() => + useDisassociateExceptionList({ + http: mockKibanaHttpService, + ruleRuleId: 'rule_id', + onError, + onSuccess, + }) + ); + + await waitFor(() => expect(result.current).toEqual([false, null])); }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/pages/coverage_overview/filter_panel.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/pages/coverage_overview/filter_panel.test.tsx index 6931298b7ed48..c0c42200c1fe9 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/pages/coverage_overview/filter_panel.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/pages/coverage_overview/filter_panel.test.tsx @@ -7,6 +7,7 @@ import { fireEvent, render, within } from '@testing-library/react'; import React from 'react'; +import userEvent from '@testing-library/user-event'; import { TestProviders } from '../../../../common/mock'; import { CoverageOverviewFiltersPanel } from './filters_panel'; @@ -51,29 +52,33 @@ const renderFiltersPanel = () => { }; describe('CoverageOverviewFiltersPanel', () => { - test('it correctly populates rule activity filter state', () => { + test('it correctly populates rule activity filter state', async () => { const wrapper = renderFiltersPanel(); - wrapper.getByTestId('coverageOverviewRuleActivityFilterButton').click(); + await userEvent.click(wrapper.getByTestId('coverageOverviewRuleActivityFilterButton')); - within(wrapper.getByTestId('coverageOverviewFilterList')) - .getByText(ruleActivityFilterLabelMap[ruleActivityFilterDefaultOptions[0].label]) - .click(); + await userEvent.click( + within(wrapper.getByTestId('coverageOverviewFilterList')).getByText( + ruleActivityFilterLabelMap[ruleActivityFilterDefaultOptions[0].label] + ) + ); expect(setRuleActivityFilter).toHaveBeenCalledWith([ruleActivityFilterDefaultOptions[0].label]); }); - test('it correctly populates rule source filter state', () => { + test('it correctly populates rule source filter state', async () => { const wrapper = renderFiltersPanel(); - wrapper.getByTestId('coverageOverviewRuleSourceFilterButton').click(); + await userEvent.click(wrapper.getByTestId('coverageOverviewRuleSourceFilterButton')); - within(wrapper.getByTestId('coverageOverviewFilterList')) - .getByText(ruleSourceFilterLabelMap[ruleSourceFilterDefaultOptions[0].label]) - .click(); + await userEvent.click( + within(wrapper.getByTestId('coverageOverviewFilterList')).getByText( + ruleSourceFilterLabelMap[ruleSourceFilterDefaultOptions[0].label] + ) + ); expect(setRuleSourceFilter).toHaveBeenCalledWith([ruleSourceFilterDefaultOptions[0].label]); }); - test('it correctly populates search filter state', () => { + test('it correctly populates search filter state', async () => { const wrapper = renderFiltersPanel(); fireEvent.change(wrapper.getByTestId('coverageOverviewFilterSearchBar'), { diff --git a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/pages/rule_management/__integration_tests__/rules_upgrade/test_utils/rule_upgrade_flyout.tsx b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/pages/rule_management/__integration_tests__/rules_upgrade/test_utils/rule_upgrade_flyout.tsx index 3908cb2d79bab..0d6900afc47e6 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/pages/rule_management/__integration_tests__/rules_upgrade/test_utils/rule_upgrade_flyout.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detection_engine/rule_management_ui/pages/rule_management/__integration_tests__/rules_upgrade/test_utils/rule_upgrade_flyout.tsx @@ -6,13 +6,14 @@ */ import React from 'react'; -import { render, act, fireEvent, screen } from '@testing-library/react'; +import { render, screen } from '@testing-library/react'; import type { DataViewField, DataViewFieldMap, DataViewSpec, FieldSpec, } from '@kbn/data-views-plugin/common'; +import userEvent from '@testing-library/user-event'; import { invariant } from '../../../../../../../../common/utils/invariant'; import { TIMELINES_URL } from '../../../../../../../../common/constants'; import { RulesPage } from '../../..'; @@ -207,9 +208,7 @@ export function mockKibanaFetchResponse(path: string, mockResponse: unknown): vo } async function openRuleUpgradeFlyout(): Promise { - await act(async () => { - fireEvent.click(await screen.findByTestId('ruleName')); - }); + await userEvent.click(await screen.findByTestId('ruleName')); } const createMockDataView = ({ id, title, fields }: DataViewSpec) => diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alert_summary/search_bar/integrations_filter_button.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alert_summary/search_bar/integrations_filter_button.test.tsx index fb4f97b0f5bfd..e00a47690e35d 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alert_summary/search_bar/integrations_filter_button.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alert_summary/search_bar/integrations_filter_button.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { act, render } from '@testing-library/react'; +import { render, waitFor } from '@testing-library/react'; import { useKibana } from '../../../../common/lib/kibana'; import { FILTER_KEY, @@ -15,6 +15,7 @@ import { INTEGRATIONS_LIST_TEST_ID, } from './integrations_filter_button'; import type { EuiSelectableOption } from '@elastic/eui/src/components/selectable/selectable_option'; +import userEvent from '@testing-library/user-event'; jest.mock('../../../../common/lib/kibana'); @@ -38,20 +39,16 @@ describe('', () => { services: { data: { query: { filterManager: jest.fn() } } }, }); - await act(async () => { - const { getByTestId } = render(); + const { getByTestId } = render(); - const button = getByTestId(INTEGRATION_BUTTON_TEST_ID); - expect(button).toBeInTheDocument(); - button.click(); + const button = getByTestId(INTEGRATION_BUTTON_TEST_ID); + expect(button).toBeInTheDocument(); + await userEvent.click(button); - await new Promise(process.nextTick); + expect(getByTestId(INTEGRATIONS_LIST_TEST_ID)).toBeInTheDocument(); - expect(getByTestId(INTEGRATIONS_LIST_TEST_ID)).toBeInTheDocument(); - - expect(getByTestId('first')).toHaveTextContent('firstLabel'); - expect(getByTestId('second')).toHaveTextContent('secondLabel'); - }); + expect(getByTestId('first')).toHaveTextContent('firstLabel'); + expect(getByTestId('second')).toHaveTextContent('secondLabel'); }); it('should add a negated filter to filterManager', async () => { @@ -61,29 +58,30 @@ describe('', () => { services: { data: { query: { filterManager: { getFilters, setFilters } } } }, }); - await act(async () => { - const { getByTestId } = render(); - - getByTestId(INTEGRATION_BUTTON_TEST_ID).click(); - - await new Promise(process.nextTick); - - getByTestId('first').click(); - expect(setFilters).toHaveBeenCalledWith([ - { - meta: { - alias: null, - disabled: false, - index: undefined, - key: FILTER_KEY, - negate: true, - params: { query: 'firstKey' }, - type: 'phrase', - }, - query: { match_phrase: { [FILTER_KEY]: 'firstKey' } }, - }, - ]); + const { getByTestId } = render(); + + await userEvent.click(getByTestId(INTEGRATION_BUTTON_TEST_ID)); + + await waitFor(() => { + expect(getByTestId('first')).toBeVisible(); }); + + await userEvent.click(getByTestId('first')); + + expect(setFilters).toHaveBeenCalledWith([ + { + meta: { + alias: null, + disabled: false, + index: undefined, + key: FILTER_KEY, + negate: true, + params: { query: 'firstKey' }, + type: 'phrase', + }, + query: { match_phrase: { [FILTER_KEY]: 'firstKey' } }, + }, + ]); }); it('should remove the negated filter from filterManager', async () => { @@ -106,16 +104,16 @@ describe('', () => { services: { data: { query: { filterManager: { getFilters, setFilters } } } }, }); - await act(async () => { - const { getByTestId } = render(); + const { getByTestId } = render(); - getByTestId(INTEGRATION_BUTTON_TEST_ID).click(); + await userEvent.click(getByTestId(INTEGRATION_BUTTON_TEST_ID)); - await new Promise(process.nextTick); - - // creates a new filter that - getByTestId('second').click(); - expect(setFilters).toHaveBeenCalledWith([]); + await waitFor(() => { + expect(getByTestId('second')).toBeVisible(); }); + + // creates a new filter that + await userEvent.click(getByTestId('second')); + expect(setFilters).toHaveBeenCalledWith([]); }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alert_summary/table/more_actions_row_control_column.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alert_summary/table/more_actions_row_control_column.test.tsx index 96dfafcbdbe2f..1c16d53c02f71 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alert_summary/table/more_actions_row_control_column.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alert_summary/table/more_actions_row_control_column.test.tsx @@ -15,12 +15,13 @@ import type { EcsSecurityExtension as Ecs } from '@kbn/securitysolution-ecs'; import { useKibana } from '../../../../common/lib/kibana'; import { mockCasesContract } from '@kbn/cases-plugin/public/mocks'; import { useAlertsPrivileges } from '../../../containers/detection_engine/alerts/use_alerts_privileges'; +import userEvent from '@testing-library/user-event'; jest.mock('../../../../common/lib/kibana'); jest.mock('../../../containers/detection_engine/alerts/use_alerts_privileges'); describe('MoreActionsRowControlColumn', () => { - it('should render component with all options', () => { + it('should render component with all options', async () => { (useAlertsPrivileges as jest.Mock).mockReturnValue({ hasIndexWrite: true }); (useKibana as jest.Mock).mockReturnValue({ services: { @@ -49,14 +50,14 @@ describe('MoreActionsRowControlColumn', () => { const button = getByTestId(MORE_ACTIONS_BUTTON_TEST_ID); expect(button).toBeInTheDocument(); - button.click(); + await userEvent.click(button); expect(getByTestId('add-to-existing-case-action')).toBeInTheDocument(); expect(getByTestId('add-to-new-case-action')).toBeInTheDocument(); expect(getByTestId('alert-tags-context-menu-item')).toBeInTheDocument(); }); - it('should not show cases actions if user is not authorized', () => { + it('should not show cases actions if user is not authorized', async () => { (useAlertsPrivileges as jest.Mock).mockReturnValue({ hasIndexWrite: true }); (useKibana as jest.Mock).mockReturnValue({ services: { @@ -87,13 +88,13 @@ describe('MoreActionsRowControlColumn', () => { const button = getByTestId(MORE_ACTIONS_BUTTON_TEST_ID); expect(button).toBeInTheDocument(); - button.click(); + await userEvent.click(button); expect(queryByTestId('add-to-existing-case-action')).not.toBeInTheDocument(); expect(queryByTestId('add-to-new-case-action')).not.toBeInTheDocument(); }); - it('should not show tags actions if user is not authorized', () => { + it('should not show tags actions if user is not authorized', async () => { (useAlertsPrivileges as jest.Mock).mockReturnValue({ hasIndexWrite: false }); (useKibana as jest.Mock).mockReturnValue({ services: { @@ -124,7 +125,7 @@ describe('MoreActionsRowControlColumn', () => { const button = getByTestId(MORE_ACTIONS_BUTTON_TEST_ID); expect(button).toBeInTheDocument(); - button.click(); + await userEvent.click(button); expect(queryByTestId('alert-tags-context-menu-item')).not.toBeInTheDocument(); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_count_panel/index.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_count_panel/index.test.tsx index 64a6aa2ae7a50..e2dfeb22bc13e 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_count_panel/index.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_count_panel/index.test.tsx @@ -120,16 +120,17 @@ it('it does NOT render the inspect button when a `chartOptionsContextMenu` is pr }); describe('toggleQuery', () => { - it('toggles', async () => { - await act(async () => { - const { getByTestId } = render( - - - - ); + it('toggles', () => { + const { getByTestId } = render( + + + + ); + act(() => { fireEvent.click(getByTestId('query-toggle-header')); - expect(mockSetIsExpanded).toBeCalledWith(false); }); + + expect(mockSetIsExpanded).toBeCalledWith(false); }); it('when isExpanded is true, render counts panel', () => { diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_progress_bar_panel/index.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_progress_bar_panel/index.test.tsx index f0c7fd7834735..a32533e1bb7c2 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_progress_bar_panel/index.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_progress_bar_panel/index.test.tsx @@ -84,17 +84,18 @@ describe('Alert by grouping', () => { }); test('combo box renders corrected options', async () => { + render( + + + + ); + const comboBox = screen.getByRole('combobox', { name: STACK_BY_ARIA_LABEL }); act(() => { - render( - - - - ); - const comboBox = screen.getByRole('combobox', { name: STACK_BY_ARIA_LABEL }); if (comboBox) { comboBox.focus(); // display the combo box options } }); + const optionsFound = screen.getAllByRole('option').map((option) => option.textContent); options.forEach((option, i) => { expect(optionsFound[i]).toEqual(option); @@ -103,19 +104,22 @@ describe('Alert by grouping', () => { test('it invokes setGroupBySelection when an option is selected', async () => { const toBeSelected = 'user.name'; + render( + + + + ); + const comboBox = screen.getByRole('combobox', { name: STACK_BY_ARIA_LABEL }); act(() => { - render( - - - - ); - const comboBox = screen.getByRole('combobox', { name: STACK_BY_ARIA_LABEL }); if (comboBox) { comboBox.focus(); // display the combo box options } }); + const button = await screen.findByText(toBeSelected); - fireEvent.click(button); + act(() => { + fireEvent.click(button); + }); expect(setGroupBySelection).toBeCalledWith(toBeSelected); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_summary_charts_panel/index.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_summary_charts_panel/index.test.tsx index 6038910bc407b..8aab42e2f15ab 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_summary_charts_panel/index.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/components/alerts_kpis/alerts_summary_charts_panel/index.test.tsx @@ -86,18 +86,19 @@ describe('AlertsSummaryChartsPanel', () => { describe('toggleQuery', () => { test('toggles', async () => { - await act(async () => { - const { container } = render( - - - - ); - const element = container.querySelector('[data-test-subj="query-toggle-header"]'); + const { container } = render( + + + + ); + const element = container.querySelector('[data-test-subj="query-toggle-header"]'); + act(() => { if (element) { fireEvent.click(element); } - expect(mockSetIsExpanded).toBeCalledWith(false); }); + + expect(mockSetIsExpanded).toBeCalledWith(false); }); it('when isExpanded is true, render summary chart', () => { diff --git a/x-pack/solutions/security/plugins/security_solution/public/detections/pages/alert_summary/alert_summary.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/detections/pages/alert_summary/alert_summary.test.tsx index 8dbe827ca7c2c..a355ae507c1df 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/detections/pages/alert_summary/alert_summary.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/detections/pages/alert_summary/alert_summary.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { act, render } from '@testing-library/react'; +import { render } from '@testing-library/react'; import { AlertSummaryPage, LOADING_INTEGRATIONS_TEST_ID } from './alert_summary'; import { useFetchIntegrations } from '../../hooks/alert_summary/use_fetch_integrations'; import { LANDING_PAGE_PROMPT_TEST_ID } from '../../components/alert_summary/landing_page/landing_page'; @@ -78,11 +78,9 @@ describe('', () => { isLoading: false, }); - await act(async () => { - const { getByTestId, queryByTestId } = render(); - expect(queryByTestId(LOADING_INTEGRATIONS_TEST_ID)).not.toBeInTheDocument(); - expect(queryByTestId(LANDING_PAGE_PROMPT_TEST_ID)).not.toBeInTheDocument(); - expect(getByTestId(DATA_VIEW_LOADING_PROMPT_TEST_ID)).toBeInTheDocument(); - }); + const { getByTestId, queryByTestId } = render(); + expect(queryByTestId(LOADING_INTEGRATIONS_TEST_ID)).not.toBeInTheDocument(); + expect(queryByTestId(LANDING_PAGE_PROMPT_TEST_ID)).not.toBeInTheDocument(); + expect(getByTestId(DATA_VIEW_LOADING_PROMPT_TEST_ID)).toBeInTheDocument(); }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_store/components/enablement_modal.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_store/components/enablement_modal.test.tsx index b479d854a423e..31bdb7c99814d 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_store/components/enablement_modal.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/entity_analytics/components/entity_store/components/enablement_modal.test.tsx @@ -6,7 +6,6 @@ */ import React from 'react'; -import { act } from 'react-dom/test-utils'; import { fireEvent, render, screen } from '@testing-library/react'; import type { EntityStoreEnablementModalProps } from './enablement_modal'; import { EntityStoreEnablementModal } from './enablement_modal'; @@ -88,9 +87,9 @@ const missingRiskEnginePrivileges: RiskEngineMissingPrivilegesResponse = { }, }; -const renderComponent = async (props: EntityStoreEnablementModalProps = defaultProps) => { - await act(async () => { - return render(, { wrapper: TestProviders }); +const renderComponent = (props: EntityStoreEnablementModalProps = defaultProps) => { + return render(, { + wrapper: TestProviders, }); }; diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/ai_for_soc/components/settings_menu.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/ai_for_soc/components/settings_menu.test.tsx index 722d4f244f10d..6ff814e3d072d 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/ai_for_soc/components/settings_menu.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/ai_for_soc/components/settings_menu.test.tsx @@ -14,6 +14,7 @@ import { } from './settings_menu'; import { ALERT_SUMMARY_ANONYMIZE_TOGGLE_TEST_ID } from './anonymization_switch'; import { AIForSOCDetailsContext } from '../context'; +import userEvent from '@testing-library/user-event'; const mockContextValue = { showAnonymizedValues: false, @@ -21,7 +22,7 @@ const mockContextValue = { } as unknown as AIForSOCDetailsContext; describe('AlertSummaryOptionsMenu', () => { - it('renders button with the anonymize option', () => { + it('renders button with the anonymize option', async () => { const { getByTestId } = render( @@ -31,8 +32,7 @@ describe('AlertSummaryOptionsMenu', () => { const button = getByTestId(ALERT_SUMMARY_OPTIONS_MENU_BUTTON_TEST_ID); expect(button).toBeInTheDocument(); - - button.click(); + await userEvent.click(button); expect(getByTestId(ALERT_SUMMARY_ANONYMIZE_TOGGLE_TEST_ID)).toBeInTheDocument(); expect(getByTestId(ALERT_SUMMARY_OPTIONS_MENU_PANELS_TEST_ID)).toHaveTextContent('Options'); diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/ai_for_soc/components/take_action_button.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/ai_for_soc/components/take_action_button.test.tsx index 103742dc56864..89ad94da6abf1 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/ai_for_soc/components/take_action_button.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/ai_for_soc/components/take_action_button.test.tsx @@ -12,13 +12,14 @@ import { mockCasesContract } from '@kbn/cases-plugin/public/mocks'; import { TAKE_ACTION_BUTTON_TEST_ID, TakeActionButton } from './take_action_button'; import { useAlertsPrivileges } from '../../../detections/containers/detection_engine/alerts/use_alerts_privileges'; import { useAIForSOCDetailsContext } from '../context'; +import userEvent from '@testing-library/user-event'; jest.mock('../../../common/lib/kibana'); jest.mock('../../../detections/containers/detection_engine/alerts/use_alerts_privileges'); jest.mock('../context'); describe('TakeActionButton', () => { - it('should render component with all options', () => { + it('should render component with all options', async () => { (useAlertsPrivileges as jest.Mock).mockReturnValue({ hasIndexWrite: true }); (useKibana as jest.Mock).mockReturnValue({ services: { @@ -48,14 +49,14 @@ describe('TakeActionButton', () => { const button = getByTestId(TAKE_ACTION_BUTTON_TEST_ID); expect(button).toBeInTheDocument(); - button.click(); + await userEvent.click(button); expect(getByTestId('add-to-existing-case-action')).toBeInTheDocument(); expect(getByTestId('add-to-new-case-action')).toBeInTheDocument(); expect(getByTestId('alert-tags-context-menu-item')).toBeInTheDocument(); }); - it('should not show cases actions if user is not authorized', () => { + it('should not show cases actions if user is not authorized', async () => { (useAlertsPrivileges as jest.Mock).mockReturnValue({ hasIndexWrite: true }); (useKibana as jest.Mock).mockReturnValue({ services: { @@ -85,13 +86,13 @@ describe('TakeActionButton', () => { const button = getByTestId(TAKE_ACTION_BUTTON_TEST_ID); expect(button).toBeInTheDocument(); - button.click(); + await userEvent.click(button); expect(queryByTestId('add-to-existing-case-action')).not.toBeInTheDocument(); expect(queryByTestId('add-to-new-case-action')).not.toBeInTheDocument(); }); - it('should not show tags actions if user is not authorized', () => { + it('should not show tags actions if user is not authorized', async () => { (useAlertsPrivileges as jest.Mock).mockReturnValue({ hasIndexWrite: false }); (useKibana as jest.Mock).mockReturnValue({ services: { @@ -121,7 +122,7 @@ describe('TakeActionButton', () => { const button = getByTestId(TAKE_ACTION_BUTTON_TEST_ID); expect(button).toBeInTheDocument(); - button.click(); + await userEvent.click(button); expect(queryByTestId('alert-tags-context-menu-item')).not.toBeInTheDocument(); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/status.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/status.test.tsx index 9cb3d61343875..36678b482d60e 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/status.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/status.test.tsx @@ -14,6 +14,7 @@ import { TestProviders } from '../../../../common/mock'; import { useAlertsActions } from '../../../../detections/components/alerts_table/timeline_actions/use_alerts_actions'; import { STATUS_BUTTON_TEST_ID } from './test_ids'; import { TestProvider } from '@kbn/expandable-flyout/src/test/provider'; +import userEvent from '@testing-library/user-event'; jest.mock('../../../../detections/components/alerts_table/timeline_actions/use_alerts_actions'); @@ -39,7 +40,7 @@ const actionItem = { }); describe('', () => { - it('should render status information', () => { + it('should render status information', async () => { const contextValue = { eventId: 'eventId', browserFields: {}, @@ -52,7 +53,7 @@ describe('', () => { expect(getByTestId(STATUS_BUTTON_TEST_ID)).toBeInTheDocument(); expect(getByText('open')).toBeInTheDocument(); - getByTestId(STATUS_BUTTON_TEST_ID).click(); + await userEvent.click(getByTestId(STATUS_BUTTON_TEST_ID)); expect(getByTestId('data-test-subj')).toBeInTheDocument(); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_tab_setting_button.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_tab_setting_button.test.tsx index 9cc53810123c2..334de70de3025 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_tab_setting_button.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/document_details/right/components/table_tab_setting_button.test.tsx @@ -32,7 +32,9 @@ const renderComponent = () => { setTableTabState={mockSetTableTabState} isPopoverOpen={false} setIsPopoverOpen={mockSetIsPopoverOpen} - /> + />, + // TODO: fails with concurrent mode + { legacyRoot: true } ); }; diff --git a/x-pack/solutions/security/plugins/security_solution/public/flyout/shared/components/expandable_panel.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/flyout/shared/components/expandable_panel.test.tsx index 2be968669057c..2becc6898b340 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/flyout/shared/components/expandable_panel.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/flyout/shared/components/expandable_panel.test.tsx @@ -16,6 +16,7 @@ import { } from './test_ids'; import { EuiThemeProvider as ThemeProvider } from '@elastic/eui'; import { ExpandablePanel } from './expandable_panel'; +import userEvent from '@testing-library/user-event'; const TEST_ID = 'test-id'; const defaultProps = { @@ -131,7 +132,7 @@ describe('', () => { expect(queryByTestId(EXPANDABLE_PANEL_CONTENT_TEST_ID(TEST_ID))).not.toBeInTheDocument(); }); - it('click toggle button should expand the panel', () => { + it('click toggle button should expand the panel', async () => { const { getByTestId } = render( {children} @@ -140,7 +141,7 @@ describe('', () => { const toggle = getByTestId(EXPANDABLE_PANEL_TOGGLE_ICON_TEST_ID(TEST_ID)); expect(toggle.firstChild).toHaveAttribute('data-euiicon-type', 'arrowRight'); - toggle.click(); + await userEvent.click(toggle); expect(getByTestId(EXPANDABLE_PANEL_CONTENT_TEST_ID(TEST_ID))).toHaveTextContent( 'test content' @@ -180,7 +181,7 @@ describe('', () => { expect(getByTestId(EXPANDABLE_PANEL_TOGGLE_ICON_TEST_ID(TEST_ID))).toBeInTheDocument(); }); - it('click toggle button should collapse the panel', () => { + it('click toggle button should collapse the panel', async () => { const { getByTestId, queryByTestId } = render( {children} @@ -191,7 +192,7 @@ describe('', () => { expect(toggle.firstChild).toHaveAttribute('data-euiicon-type', 'arrowDown'); expect(getByTestId(EXPANDABLE_PANEL_CONTENT_TEST_ID(TEST_ID))).toBeInTheDocument(); - toggle.click(); + await userEvent.click(toggle); expect(toggle.firstChild).toHaveAttribute('data-euiicon-type', 'arrowRight'); expect(queryByTestId(EXPANDABLE_PANEL_CONTENT_TEST_ID(TEST_ID))).not.toBeInTheDocument(); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.test.tsx index 28d730aa56ac5..8e9542e128a77 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/artifact_list_page/components/artifact_flyout.test.tsx @@ -180,9 +180,7 @@ describe('When the flyout is opened in the ArtifactListPage component', () => { let getByTestId: (typeof renderResult)['getByTestId']; beforeEach(async () => { - await act(async () => { - await render(); - }); + await render(); getByTestId = renderResult.getByTestId; @@ -222,9 +220,7 @@ describe('When the flyout is opened in the ArtifactListPage component', () => { describe('and submit is successful', () => { beforeEach(async () => { - await act(async () => { - await render(); - }); + await render(); await userEvent.click(renderResult.getByTestId('testPage-flyout-submitButton')); @@ -304,9 +300,7 @@ describe('When the flyout is opened in the ArtifactListPage component', () => { return new ExceptionsListItemGenerator().generateTrustedApp(item); }); - await act(async () => { - await render({ onFormSubmit: handleSubmitCallback }); - }); + await render({ onFormSubmit: handleSubmitCallback }); await userEvent.click(renderResult.getByTestId('testPage-flyout-submitButton')); }); @@ -458,9 +452,7 @@ describe('When the flyout is opened in the ArtifactListPage component', () => { it('should show error toast and close flyout if item for edit does not exist', async () => { mockedApi.responseProvider.trustedApp.mockRejectedValue(new Error('does not exist') as never); - await act(async () => { - await render(); - }); + await render(); await waitFor(() => { expect(mockedApi.responseProvider.trustedApp).toHaveBeenCalled(); diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/console/components/command_list.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/components/console/components/command_list.test.tsx index 62ef40ec27668..0b096e69a86d0 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/components/console/components/command_list.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/console/components/command_list.test.tsx @@ -5,6 +5,7 @@ * 2.0. */ +import { act } from '@testing-library/react'; import type { ConsoleTestSetup, HelpSidePanelSelectorsAndActions } from '../mocks'; import { getCommandListMock, @@ -35,6 +36,7 @@ describe('When rendering the command list (help output)', () => { renderAndOpenHelpPanel = (props) => { render(props); helpPanelSelectors = getHelpSidePanelSelectorsAndActionsMock(renderResult); + consoleSelectors.openHelpPanel(); return renderResult; @@ -121,7 +123,10 @@ describe('When rendering the command list (help output)', () => { it('should add command to console input when [+] button is clicked', () => { renderAndOpenHelpPanel(); - renderResult.getByTestId('test-commandList-group1-cmd6-addToInput').click(); + act(() => { + renderResult.getByTestId('test-commandList-group1-cmd6-addToInput').click(); + }); + expect(consoleSelectors.getInputText()).toEqual('cmd6 --foo '); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/console/components/console_header.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/components/console/components/console_header.test.tsx index 4457347832eac..d07644c4733f7 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/components/console/components/console_header.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/console/components/console_header.test.tsx @@ -10,6 +10,7 @@ import type { ConsoleProps } from '..'; import type { AppContextTestRender } from '../../../../common/mock/endpoint'; import { getConsoleTestSetup } from '../mocks'; import { HELP_LABEL } from './console_header'; +import { act } from '@testing-library/react'; describe('Console header area', () => { let render: (props?: Partial) => ReturnType; @@ -43,7 +44,9 @@ describe('Console header area', () => { it('should open the side panel when help button is clicked', () => { render(); - renderResult.getByTestId('test-header-helpButton').click(); + act(() => { + renderResult.getByTestId('test-header-helpButton').click(); + }); expect(renderResult.getByTestId('test-sidePanel')).toBeTruthy(); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/console/mocks.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/components/console/mocks.tsx index 0506a01d0dc66..6076c83fba615 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/components/console/mocks.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/console/mocks.tsx @@ -10,7 +10,7 @@ import React, { memo, useEffect } from 'react'; import { EuiCode } from '@elastic/eui'; import userEvent, { type UserEvent } from '@testing-library/user-event'; -import { fireEvent, within } from '@testing-library/react'; +import { act, fireEvent, within } from '@testing-library/react'; import { convertToTestId } from './components/command_list'; import { Console } from './console'; import type { @@ -88,16 +88,22 @@ export const getConsoleSelectorsAndActionMock = ( const openHelpPanel: ConsoleSelectorsAndActionsMock['openHelpPanel'] = () => { if (!isHelpPanelOpen()) { - renderResult.getByTestId(`${dataTestSubj}-header-helpButton`).click(); + act(() => { + renderResult.getByTestId(`${dataTestSubj}-header-helpButton`).click(); + }); } }; const closeHelpPanel: ConsoleSelectorsAndActionsMock['closeHelpPanel'] = () => { if (isHelpPanelOpen()) { - renderResult.getByTestId(`${dataTestSubj}-sidePanel-headerCloseButton`).click(); + act(() => { + renderResult.getByTestId(`${dataTestSubj}-sidePanel-headerCloseButton`).click(); + }); } }; const submitCommand: ConsoleSelectorsAndActionsMock['submitCommand'] = () => { - renderResult.getByTestId(`${dataTestSubj}-inputTextSubmitButton`).click(); + act(() => { + renderResult.getByTestId(`${dataTestSubj}-inputTextSubmitButton`).click(); + }); }; const enterCommand: ConsoleSelectorsAndActionsMock['enterCommand'] = async ( cmd, diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/context_menu_with_router_support/context_menu_with_router_support.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/components/context_menu_with_router_support/context_menu_with_router_support.test.tsx index 5ecbd5240fd15..4928251444c69 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/components/context_menu_with_router_support/context_menu_with_router_support.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/context_menu_with_router_support/context_menu_with_router_support.test.tsx @@ -99,11 +99,9 @@ describe('When using the ContextMenuWithRouterSupport component', () => { it('should close menu when a menu item is clicked and call menu item onclick callback', async () => { render(); clickMenuTriggerButton(); - await act(async () => { - const menuPanelRemoval = waitForElementToBeRemoved(getContextMenuPanel()); - fireEvent.click(renderResult.getByTestId('menu-item-one')); - await menuPanelRemoval; - }); + const menuPanelRemoval = waitForElementToBeRemoved(getContextMenuPanel()); + fireEvent.click(renderResult.getByTestId('menu-item-one')); + await menuPanelRemoval; expect(getContextMenuPanel()).toBeNull(); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_response_actions_list/integration_tests/response_actions_log.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_response_actions_list/integration_tests/response_actions_log.test.tsx index 521ebe3614acf..dc8b208e3d1d9 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_response_actions_list/integration_tests/response_actions_log.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/components/endpoint_response_actions_list/integration_tests/response_actions_log.test.tsx @@ -941,19 +941,19 @@ describe('Response actions history', () => { }); }); - it('should display pending output if action is not complete yet', () => { + it('should display pending output if action is not complete yet', async () => { action.isCompleted = false; const { getByTestId } = render(); - getByTestId(`${testPrefix}-expand-button`).click(); + await user.click(getByTestId(`${testPrefix}-expand-button`)); expect(getByTestId(`${testPrefix}-details-tray-output`)).toHaveTextContent( OUTPUT_MESSAGES.isPending('upload') ); }); - it('should display output for single agent', () => { + it('should display output for single agent', async () => { const { getByTestId } = render(); - getByTestId(`${testPrefix}-expand-button`).click(); + await user.click(getByTestId(`${testPrefix}-expand-button`)); expect(getByTestId(`${testPrefix}-uploadDetails`)).toHaveTextContent( 'upload completed successfully' + @@ -962,7 +962,7 @@ describe('Response actions history', () => { ); }); - it('should display output for multiple agents', () => { + it('should display output for multiple agents', async () => { action.agents.push('agent-b'); action.hosts['agent-b'] = { name: 'host b', @@ -983,7 +983,8 @@ describe('Response actions history', () => { }; const { getByTestId } = render(); - getByTestId(`${testPrefix}-expand-button`).click(); + + await user.click(getByTestId(`${testPrefix}-expand-button`)); expect(getByTestId(`${testPrefix}-uploadDetails`)).toHaveTextContent( 'upload completed successfully' + diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/integration_tests/search_bar.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/integration_tests/search_bar.test.tsx index f053ee5ef8d68..2cd77301a5deb 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/integration_tests/search_bar.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/pages/endpoint_hosts/view/components/integration_tests/search_bar.test.tsx @@ -47,12 +47,12 @@ describe('when rendering the endpoint list `AdminSearchBar`', () => { }); // Wait for the search bar to actually display our value - await act(async () => { - await waitFor(() => !!searchBarInput.value); - }); + await waitFor(() => !!searchBarInput.value); await act(async () => { fireEvent.click(querySubmitButton); + }); + await act(async () => { await changeUrlActionDone; }); }; diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/pages/event_filters/view/integration_tests/event_filters_list.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/pages/event_filters/view/integration_tests/event_filters_list.test.tsx index bc752725069d1..5a0557a9360f8 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/pages/event_filters/view/integration_tests/event_filters_list.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/pages/event_filters/view/integration_tests/event_filters_list.test.tsx @@ -91,10 +91,8 @@ describe('When on the Event Filters list page', () => { render(); - await act(async () => { - await waitFor(() => { - expect(renderResult.getByTestId('EventFiltersListPage-list')).toBeTruthy(); - }); + await waitFor(() => { + expect(renderResult.getByTestId('EventFiltersListPage-list')).toBeTruthy(); }); return renderResult; diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/artifacts/list/policy_artifacts_list.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/artifacts/list/policy_artifacts_list.test.tsx index 1bce9cb0a88eb..597b0f3d9a14c 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/artifacts/list/policy_artifacts_list.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/artifacts/list/policy_artifacts_list.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { act, waitFor } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import { getFoundExceptionListItemSchemaMock } from '@kbn/lists-plugin/common/schemas/response/found_exception_list_item_schema.mock'; @@ -57,25 +57,23 @@ describe('Policy details artifacts list', () => { canCreateArtifactsByPolicy: true, }); render = async (canWriteArtifact = true) => { - await act(async () => { - renderResult = mockedContext.render( - - ); - await waitFor(() => expect(mockedApi.responseProvider.eventFiltersList).toHaveBeenCalled()); - await waitFor(() => - expect(renderResult.queryByTestId('artifacts-collapsed-list-loader')).toBeFalsy() - ); - }); + renderResult = mockedContext.render( + + ); + await waitFor(() => expect(mockedApi.responseProvider.eventFiltersList).toHaveBeenCalled()); + await waitFor(() => + expect(renderResult.queryByTestId('artifacts-collapsed-list-loader')).toBeFalsy() + ); return renderResult; }; diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_edit_extension/components/fleet_integration_artifacts_card.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_edit_extension/components/fleet_integration_artifacts_card.test.tsx index e34789bb6a713..6e33d3849573e 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_edit_extension/components/fleet_integration_artifacts_card.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/ingest_manager_integration/endpoint_policy_edit_extension/components/fleet_integration_artifacts_card.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { waitFor, act } from '@testing-library/react'; +import { waitFor } from '@testing-library/react'; import * as reactTestingLibrary from '@testing-library/react'; import type { AppContextTestRender } from '../../../../../../../common/mock/endpoint'; import { createAppRootMockRenderer } from '../../../../../../../common/mock/endpoint'; @@ -37,24 +37,22 @@ describe('Fleet integration policy endpoint security event filters card', () => mockedApi = eventFiltersListQueryHttpMock(mockedContext.coreStart.http); ({ history } = mockedContext); render = async (externalPrivileges = true) => { - await act(async () => { - renderResult = mockedContext.render( - - ); - await waitFor(() => - expect(mockedApi.responseProvider.eventFiltersGetSummary).toHaveBeenCalled() - ); - }); + renderResult = mockedContext.render( + + ); + await waitFor(() => + expect(mockedApi.responseProvider.eventFiltersGetSummary).toHaveBeenCalled() + ); return renderResult; }; diff --git a/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/policy_settings_form/policy_settings_form.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/policy_settings_form/policy_settings_form.test.tsx index 428da56167810..540f1786657a2 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/policy_settings_form/policy_settings_form.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/management/pages/policy/view/policy_settings_form/policy_settings_form.test.tsx @@ -81,11 +81,11 @@ describe('Endpoint Policy Settings Form', () => { expect(renderResult.getByTestId('eventMergingCallout')).toBeInTheDocument(); }); - it('should hide the event merging banner when user dismisses it', () => { + it('should hide the event merging banner when user dismisses it', async () => { render(); expect(renderResult.getByTestId('eventMergingCallout')).toBeInTheDocument(); - renderResult.getByTestId('euiDismissCalloutButton').click(); + await userEvent.click(renderResult.getByTestId('euiDismissCalloutButton')); expect(renderResult.queryByTestId('eventMergingCallout')).not.toBeInTheDocument(); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/notes/components/note_content.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/notes/components/note_content.test.tsx index 6cc9d33d886b7..b6d26f211e6c8 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/notes/components/note_content.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/notes/components/note_content.test.tsx @@ -6,6 +6,7 @@ */ import { render } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import React from 'react'; import { NoteContent } from './note_content'; import { NOTE_CONTENT_BUTTON_TEST_ID, NOTE_CONTENT_POPOVER_TEST_ID } from './test_ids'; @@ -13,7 +14,7 @@ import { NOTE_CONTENT_BUTTON_TEST_ID, NOTE_CONTENT_POPOVER_TEST_ID } from './tes const note = 'note-text'; describe('NoteContent', () => { - it('should render a note and the popover', () => { + it('should render a note and the popover', async () => { const { getByTestId, getByText } = render(); const button = getByTestId(NOTE_CONTENT_BUTTON_TEST_ID); @@ -21,7 +22,7 @@ describe('NoteContent', () => { expect(button).toBeInTheDocument(); expect(getByText(note)).toBeInTheDocument(); - button.click(); + await userEvent.click(button); expect(getByTestId(NOTE_CONTENT_POPOVER_TEST_ID)).toBeInTheDocument(); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/overview/components/signals_by_category/signals_by_category.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/overview/components/signals_by_category/signals_by_category.test.tsx index a2c63cd24b464..e8906cbb25be2 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/overview/components/signals_by_category/signals_by_category.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/overview/components/signals_by_category/signals_by_category.test.tsx @@ -6,7 +6,7 @@ */ import React from 'react'; -import { act, render } from '@testing-library/react'; +import { render } from '@testing-library/react'; import { TestProviders } from '../../../common/mock'; import { SignalsByCategory } from './signals_by_category'; @@ -43,9 +43,7 @@ const renderComponent = () => describe('SignalsByCategory', () => { it('Renders to the page', () => { - act(() => { - const { getByText } = renderComponent(); - expect(getByText('Alert trend')).toBeInTheDocument(); - }); + const { getByText } = renderComponent(); + expect(getByText('Alert trend')).toBeInTheDocument(); }); }); diff --git a/x-pack/solutions/security/plugins/security_solution/public/timelines/components/bottom_bar/add_timeline_button.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/timelines/components/bottom_bar/add_timeline_button.test.tsx index b6bbb21604755..406e08c424788 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/timelines/components/bottom_bar/add_timeline_button.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/timelines/components/bottom_bar/add_timeline_button.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { render } from '@testing-library/react'; import { AddTimelineButton } from './add_timeline_button'; import { useCreateTimeline } from '../../hooks/use_create_timeline'; +import userEvent from '@testing-library/user-event'; jest.mock('../../hooks/use_create_timeline'); @@ -16,7 +17,7 @@ const timelineId = 'timelineId'; const renderAddTimelineButton = () => render(); describe('AddTimelineButton', () => { - it('should present 3 options in the popover when clicking on the plus button', () => { + it('should present 3 options in the popover when clicking on the plus button', async () => { (useCreateTimeline as jest.Mock).mockReturnValue(jest.fn()); const { getByTestId } = renderAddTimelineButton(); @@ -25,7 +26,7 @@ describe('AddTimelineButton', () => { expect(plusButton).toBeInTheDocument(); - plusButton.click(); + await userEvent.click(plusButton); expect(getByTestId('timeline-bottom-bar-create-new-timeline')).toBeInTheDocument(); expect(getByTestId('timeline-bottom-bar-create-new-timeline')).toHaveTextContent( diff --git a/x-pack/solutions/security/plugins/security_solution/public/timelines/components/modal/actions/attach_to_case_button.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/timelines/components/modal/actions/attach_to_case_button.test.tsx index 22a9be583329d..d2b6a16774615 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/timelines/components/modal/actions/attach_to_case_button.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/timelines/components/modal/actions/attach_to_case_button.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { render } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { waitForEuiPopoverOpen } from '@elastic/eui/lib/test/rtl'; import { useKibana } from '../../../../common/lib/kibana'; import { mockTimelineModel, TestProviders } from '../../../../common/mock'; @@ -49,7 +50,7 @@ describe('AttachToCaseButton', () => { useKibanaMock().services.application.navigateToApp = navigateToApp; }); - it('should render the 2 options in the popover when clicking on the button', () => { + it('should render the 2 options in the popover when clicking on the button', async () => { const { getByTestId } = renderAttachToCaseButton(); const button = getByTestId('timeline-modal-attach-to-case-dropdown-button'); @@ -57,7 +58,7 @@ describe('AttachToCaseButton', () => { expect(button).toBeInTheDocument(); expect(button).toHaveTextContent('Attach to case'); - button.click(); + await userEvent.click(button); expect(getByTestId('timeline-modal-attach-timeline-to-new-case')).toBeInTheDocument(); expect(getByTestId('timeline-modal-attach-timeline-to-new-case')).toHaveTextContent( @@ -81,11 +82,11 @@ describe('AttachToCaseButton', () => { const { getByTestId } = renderAttachToCaseButton(); - getByTestId('timeline-modal-attach-to-case-dropdown-button').click(); + await userEvent.click(getByTestId('timeline-modal-attach-to-case-dropdown-button')); await waitForEuiPopoverOpen(); - getByTestId('timeline-modal-attach-timeline-to-existing-case').click(); + await userEvent.click(getByTestId('timeline-modal-attach-timeline-to-existing-case')); expect(navigateToApp).toHaveBeenCalledWith('securitySolutionUI', { path: '/create', @@ -103,11 +104,11 @@ describe('AttachToCaseButton', () => { const { getByTestId } = renderAttachToCaseButton(); - getByTestId('timeline-modal-attach-to-case-dropdown-button').click(); + await userEvent.click(getByTestId('timeline-modal-attach-to-case-dropdown-button')); await waitForEuiPopoverOpen(); - getByTestId('timeline-modal-attach-timeline-to-existing-case').click(); + await userEvent.click(getByTestId('timeline-modal-attach-timeline-to-existing-case')); expect(navigateToApp).toHaveBeenCalledWith('securitySolutionUI', { path: '/case-id', diff --git a/x-pack/solutions/security/plugins/security_solution/public/timelines/components/modal/actions/new_timeline_button.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/timelines/components/modal/actions/new_timeline_button.test.tsx index 91ebd96c7a0c3..23e676f4ae6a2 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/timelines/components/modal/actions/new_timeline_button.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/timelines/components/modal/actions/new_timeline_button.test.tsx @@ -6,6 +6,7 @@ */ import { render, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import React from 'react'; import { NewTimelineButton } from './new_timeline_button'; import { TimelineId } from '../../../../../common/types'; @@ -38,7 +39,7 @@ describe('NewTimelineButton', () => { expect(button).toBeInTheDocument(); expect(getByText('New')).toBeInTheDocument(); - button.click(); + await userEvent.click(button); expect(getByTestId('timeline-modal-new-timeline')).toBeInTheDocument(); expect(getByTestId('timeline-modal-new-timeline')).toHaveTextContent('New Timeline'); @@ -68,8 +69,8 @@ describe('NewTimelineButton', () => { const { getByTestId } = renderNewTimelineButton(); - getByTestId('timeline-modal-new-timeline-dropdown-button').click(); - getByTestId('timeline-modal-new-timeline').click(); + await userEvent.click(getByTestId('timeline-modal-new-timeline-dropdown-button')); + await userEvent.click(getByTestId('timeline-modal-new-timeline')); await waitFor(() => { expect(spy).toHaveBeenCalledWith({ diff --git a/x-pack/solutions/security/plugins/security_solution/public/timelines/components/timeline/tabs/lazy_timeline_tab_renderer.test.tsx b/x-pack/solutions/security/plugins/security_solution/public/timelines/components/timeline/tabs/lazy_timeline_tab_renderer.test.tsx index adda3b2043223..000947b184dcc 100644 --- a/x-pack/solutions/security/plugins/security_solution/public/timelines/components/timeline/tabs/lazy_timeline_tab_renderer.test.tsx +++ b/x-pack/solutions/security/plugins/security_solution/public/timelines/components/timeline/tabs/lazy_timeline_tab_renderer.test.tsx @@ -106,7 +106,10 @@ describe('LazyTimelineTabRenderer', () => { }); it('should re-render if the component is unmounted and remounted', () => { - const { rerender, queryByText, unmount } = render(); + const { rerender, queryByText, unmount } = render(, { + // TODO: fails in concurrent mode + legacyRoot: true, + }); unmount(); rerender(); expect(queryByText(testChildString)).toBeInTheDocument(); diff --git a/x-pack/solutions/security/plugins/session_view/public/components/detail_panel_metadata_tab/index.test.tsx b/x-pack/solutions/security/plugins/session_view/public/components/detail_panel_metadata_tab/index.test.tsx index b641c8d2d84ab..cfe02fa428208 100644 --- a/x-pack/solutions/security/plugins/session_view/public/components/detail_panel_metadata_tab/index.test.tsx +++ b/x-pack/solutions/security/plugins/session_view/public/components/detail_panel_metadata_tab/index.test.tsx @@ -14,6 +14,7 @@ import type { ProcessEventCloud, } from '../../../common'; import { DetailPanelMetadataTab } from '.'; +import userEvent from '@testing-library/user-event'; const TEST_ARCHITECTURE = 'x86_64'; const TEST_HOSTNAME = 'host-james-fleet-714-2'; @@ -136,7 +137,7 @@ describe('DetailPanelMetadataTab component', () => { expect(renderResult.queryByText(TEST_NAME)).toBeVisible(); // expand host os accordion - renderResult.queryByText('OS')?.click(); + await userEvent.click(renderResult.queryByText('OS')!); expect(renderResult.queryByText('architecture')).toBeVisible(); expect(renderResult.queryByText('os.family')).toBeVisible(); expect(renderResult.queryByText('os.full')).toBeVisible(); @@ -182,7 +183,7 @@ describe('DetailPanelMetadataTab component', () => { expect(renderResult.queryAllByText('name').length).toBe(2); // expand host os accordion - renderResult.queryByText('OS')?.click(); + await userEvent.click(renderResult.queryByText('OS')!); expect(renderResult.queryByText('architecture')).toBeVisible(); expect(renderResult.queryByText('os.family')).toBeVisible(); expect(renderResult.queryByText('os.full')).toBeVisible(); @@ -199,7 +200,7 @@ describe('DetailPanelMetadataTab component', () => { expect(renderResult.queryByText(TEST_OS_VERSION)).toBeVisible(); // expand Container Accordion - renderResult.queryByText('Container')?.click(); + await userEvent.click(renderResult.queryByText('Container')!); expect(renderResult.queryByText('image.name')).toBeVisible(); expect(renderResult.queryByText('image.tag')).toBeVisible(); expect(renderResult.queryByText('image.hash.all')).toBeVisible(); @@ -210,7 +211,7 @@ describe('DetailPanelMetadataTab component', () => { expect(renderResult.queryByText(TEST_CONTAINER_IMAGE_HASH_ALL)).toBeVisible(); // expand Orchestrator Accordion - renderResult.queryByText('Orchestrator')?.click(); + await userEvent.click(renderResult.queryByText('Orchestrator')!); expect(renderResult.queryByText('resource.name')).toBeVisible(); expect(renderResult.queryByText('resource.type')).toBeVisible(); expect(renderResult.queryByText('resource.ip')).toBeVisible(); @@ -227,7 +228,7 @@ describe('DetailPanelMetadataTab component', () => { expect(renderResult.queryByText(TEST_ORCHESTRATOR_CLUSTER_NAME)).toBeVisible(); // expand Cloud Accordion - renderResult.queryByText('Cloud')?.click(); + await userEvent.click(renderResult.queryByText('Cloud')!); expect(renderResult.queryByText('instance.name')).toBeVisible(); expect(renderResult.queryByText('provider')).toBeVisible(); expect(renderResult.queryByText('region')).toBeVisible(); diff --git a/x-pack/solutions/security/plugins/session_view/public/components/process_tree_alerts_filter/index.test.tsx b/x-pack/solutions/security/plugins/session_view/public/components/process_tree_alerts_filter/index.test.tsx index 2772a8c391e2c..eeb61fcbfc190 100644 --- a/x-pack/solutions/security/plugins/session_view/public/components/process_tree_alerts_filter/index.test.tsx +++ b/x-pack/solutions/security/plugins/session_view/public/components/process_tree_alerts_filter/index.test.tsx @@ -79,7 +79,9 @@ describe('ProcessTreeAlertsFiltersFilter component', () => { ); await userEvent.click(filterButton); - renderResult.getByTestId('sessionView:sessionViewAlertDetailsFilterItem-network').click(); + await userEvent.click( + renderResult.getByTestId('sessionView:sessionViewAlertDetailsFilterItem-network') + ); expect(mockAlertEventCategorySelectedEvent).toHaveBeenCalledTimes(1); expect(mockAlertEventCategorySelectedEvent).toHaveBeenCalledWith('network'); @@ -245,7 +247,9 @@ describe('ProcessTreeAlertsFiltersFilter component', () => { beforeEach(() => { renderResult = mockedContext.render( - + , + // TODO: fails with concurrent mode + { legacyRoot: true } ); }); it('should set the EmptyFilterButton text content to display "View: all alerts" by default ', () => { @@ -261,7 +265,9 @@ describe('ProcessTreeAlertsFiltersFilter component', () => { ); await userEvent.click(filterButton); - renderResult.getByTestId('sessionView:sessionViewAlertDetailsFilterItem-file').click(); + await userEvent.click( + renderResult.getByTestId('sessionView:sessionViewAlertDetailsFilterItem-file') + ); expect(filterButton).toHaveTextContent('View: file alerts'); }); @@ -272,7 +278,9 @@ describe('ProcessTreeAlertsFiltersFilter component', () => { ); await userEvent.click(filterButton); - renderResult.getByTestId('sessionView:sessionViewAlertDetailsFilterItem-default').click(); + await userEvent.click( + renderResult.getByTestId('sessionView:sessionViewAlertDetailsFilterItem-default') + ); expect(filterButton).toHaveTextContent(`View: ${DEFAULT_ALERT_FILTER_VALUE} alerts`); }); @@ -283,7 +291,9 @@ describe('ProcessTreeAlertsFiltersFilter component', () => { ); await userEvent.click(filterButton); - renderResult.getByTestId('sessionView:sessionViewAlertDetailsFilterItem-process').click(); + await userEvent.click( + renderResult.getByTestId('sessionView:sessionViewAlertDetailsFilterItem-process') + ); expect(filterButton).toHaveTextContent('View: process alerts'); }); @@ -294,7 +304,9 @@ describe('ProcessTreeAlertsFiltersFilter component', () => { ); await userEvent.click(filterButton); - renderResult.getByTestId('sessionView:sessionViewAlertDetailsFilterItem-network').click(); + await userEvent.click( + renderResult.getByTestId('sessionView:sessionViewAlertDetailsFilterItem-network') + ); expect(filterButton).toHaveTextContent('View: network alerts'); }); diff --git a/x-pack/solutions/security/plugins/session_view/public/components/session_view_detail_panel/index.test.tsx b/x-pack/solutions/security/plugins/session_view/public/components/session_view_detail_panel/index.test.tsx index aca9df393994b..7d8b901c97164 100644 --- a/x-pack/solutions/security/plugins/session_view/public/components/session_view_detail_panel/index.test.tsx +++ b/x-pack/solutions/security/plugins/session_view/public/components/session_view_detail_panel/index.test.tsx @@ -14,6 +14,7 @@ import { AppContextTestRender, createAppRootMockRenderer } from '../../test'; import { SessionViewDetailPanel } from '.'; import { useDateFormat } from '../../hooks'; import { ENDPOINT_INDEX } from '../../methods'; +import userEvent from '@testing-library/user-event'; jest.mock('../../hooks/use_date_format'); const mockUseDateFormat = useDateFormat as jest.Mock; @@ -58,7 +59,7 @@ describe('SessionView component', () => { it('can switch tabs to show host details', async () => { renderResult = mockedContext.render(); - renderResult.queryByText('Metadata')?.click(); + await userEvent.click(renderResult.queryByText('Metadata')!); expect(renderResult.queryByText('hostname')).toBeVisible(); expect(renderResult.queryAllByText('james-fleet-714-2')).toHaveLength(2); }); @@ -67,12 +68,12 @@ describe('SessionView component', () => { renderResult = mockedContext.render( ); - renderResult.queryByText('Alerts')?.click(); + await userEvent.click(renderResult.queryByText('Alerts')!); expect(renderResult.queryByText('List view')).toBeVisible(); }); it('alert tab disabled when no alerts', async () => { renderResult = mockedContext.render(); - renderResult.queryByText('Alerts')?.click(); + await userEvent.click(renderResult.queryByText('Alerts')!); expect(renderResult.queryByText('List view')).toBeFalsy(); }); });