Skip to content

Commit

Permalink
[React18] Migrate test suites to account for testing library upgrades…
Browse files Browse the repository at this point in the history
… security-threat-hunting-investigations (elastic#201145)

This PR migrates test suites that use `renderHook` from the library
`@testing-library/react-hooks` to adopt the equivalent and replacement
of `renderHook` from the export that is now available from
`@testing-library/react`. This work is required for the planned
migration to react18.

In this PR, usages of `waitForNextUpdate` that previously could have
been destructured from `renderHook` are now been replaced with `waitFor`
exported from `@testing-library/react`, furthermore `waitFor`
that would also have been destructured from the same renderHook result
is now been replaced with `waitFor` from the export of
`@testing-library/react`.

***Why is `waitFor` a sufficient enough replacement for
`waitForNextUpdate`, and better for testing values subject to async
computations?***

WaitFor will retry the provided callback if an error is returned, till
the configured timeout elapses. By default the retry interval is `50ms`
with a timeout value of `1000ms` that
effectively translates to at least 20 retries for assertions placed
within waitFor. See
https://testing-library.com/docs/dom-testing-library/api-async/#waitfor
for more information.
This however means that for person's writing tests, said person has to
be explicit about expectations that describe the internal state of the
hook being tested.
This implies checking for instance when a react query hook is being
rendered, there's an assertion that said hook isn't loading anymore.

In this PR you'd notice that this pattern has been adopted, with most
existing assertions following an invocation of `waitForNextUpdate` being
placed within a `waitFor`
invocation. In some cases the replacement is simply a `waitFor(() => new
Promise((resolve) => resolve(null)))` (many thanks to @kapral18, for
point out exactly why this works),
where this suffices the assertions that follow aren't placed within a
waitFor so this PR doesn't get larger than it needs to be.

It's also worth pointing out this PR might also contain changes to test
and application code to improve said existing test.

1. Review the changes in this PR.
2. If you think the changes are correct, approve the PR.

If you have any questions or need help with this PR, please leave
comments in this PR.

(cherry picked from commit 06de5f3)
  • Loading branch information
eokoneyo committed Dec 5, 2024
1 parent 4ffcaed commit a779c61
Show file tree
Hide file tree
Showing 84 changed files with 878 additions and 999 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useInitializeFromLocalStorage } from './use_initialize_from_local_storage';
import { localStorageMock } from '../../__mocks__';
import {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,15 @@
*/

import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import type { RenderHookResult } from '@testing-library/react-hooks';
import { renderHook, RenderHookResult } from '@testing-library/react';
import type { UseSectionsParams, UseSectionsResult } from './use_sections';
import { useSections } from './use_sections';
import { useExpandableFlyoutState } from '../..';

jest.mock('../..');

describe('useSections', () => {
let hookResult: RenderHookResult<UseSectionsParams, UseSectionsResult>;
let hookResult: RenderHookResult<UseSectionsResult, UseSectionsParams>;

it('should return undefined for all values if no registeredPanels', () => {
(useExpandableFlyoutState as jest.Mock).mockReturnValue({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import {
FULL_WIDTH_PADDING,
MAX_RESOLUTION_BREAKPOINT,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import type { UseInsightDataProvidersProps, Provider } from './use_insight_data_providers';

import { renderHook } from '@testing-library/react';
import type { Provider } from './use_insight_data_providers';
import type { TimelineEventsDetailsItem } from '../../../../../../common/search_strategy';
import {
useInsightDataProviders,
type UseInsightDataProvidersResult,
} from './use_insight_data_providers';
import { useInsightDataProviders } from './use_insight_data_providers';
import { mockAlertDetailsData } from '../../../event_details/mocks';

const mockAlertDetailsDataWithIsObject = mockAlertDetailsData.map((detail) => {
Expand Down Expand Up @@ -103,7 +101,7 @@ const providerWithRange: Provider[][] = [

describe('useInsightDataProviders', () => {
it('should return 2 data providers, 1 with a nested provider ANDed to it', () => {
const { result } = renderHook<UseInsightDataProvidersProps, UseInsightDataProvidersResult>(() =>
const { result } = renderHook(() =>
useInsightDataProviders({
providers: nestedAndProvider,
alertData: mockAlertDetailsDataWithIsObject,
Expand All @@ -117,7 +115,7 @@ describe('useInsightDataProviders', () => {
});

it('should return 3 data providers without any containing nested ANDs', () => {
const { result } = renderHook<UseInsightDataProvidersProps, UseInsightDataProvidersResult>(() =>
const { result } = renderHook(() =>
useInsightDataProviders({
providers: topLevelOnly,
alertData: mockAlertDetailsDataWithIsObject,
Expand All @@ -130,7 +128,7 @@ describe('useInsightDataProviders', () => {
});

it('should use the string literal if no field in the alert matches a bracketed value', () => {
const { result } = renderHook<UseInsightDataProvidersProps, UseInsightDataProvidersResult>(() =>
const { result } = renderHook(() =>
useInsightDataProviders({
providers: nonExistantField,
alertData: mockAlertDetailsDataWithIsObject,
Expand All @@ -145,7 +143,7 @@ describe('useInsightDataProviders', () => {
});

it('should use template data providers when called without alertData', () => {
const { result } = renderHook<UseInsightDataProvidersProps, UseInsightDataProvidersResult>(() =>
const { result } = renderHook(() =>
useInsightDataProviders({
providers: nestedAndProvider,
})
Expand All @@ -159,7 +157,7 @@ describe('useInsightDataProviders', () => {
});

it('should return an empty array of dataProviders and populated filters if a provider contains a range type', () => {
const { result } = renderHook<UseInsightDataProvidersProps, UseInsightDataProvidersResult>(() =>
const { result } = renderHook(() =>
useInsightDataProviders({
providers: providerWithRange,
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import type React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import type { QueryOperator } from '@kbn/timelines-plugin/common';
import { DataProviderTypeEnum } from '../../../../../../common/api/timeline';
import { useInsightQuery } from './use_insight_query';
import { TestProviders } from '../../../../mock';
import type { UseInsightQuery, UseInsightQueryResult } from './use_insight_query';
import { IS_OPERATOR } from '../../../../../timelines/components/timeline/data_providers/data_provider';

const mockProvider = {
Expand All @@ -30,7 +28,7 @@ const mockProvider = {

describe('useInsightQuery', () => {
it('should return renderable defaults', () => {
const { result } = renderHook<React.PropsWithChildren<UseInsightQuery>, UseInsightQueryResult>(
const { result } = renderHook(
() =>
useInsightQuery({
dataProviders: [mockProvider],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import type { PropsWithChildren } from 'react';
import { renderHook } from '@testing-library/react';
import { TestProviders } from '../../../../common/mock';
import { ALERTS_QUERY_NAMES } from '../../../containers/detection_engine/alerts/constants';
import type { UseAlerts, UseAlertsQueryProps } from './use_summary_chart_data';
import type { UseAlertsQueryProps } from './use_summary_chart_data';
import { useSummaryChartData, getAlertsQuery } from './use_summary_chart_data';
import * as aggregations from './aggregations';
import * as severityMock from '../severity_level_panel/mock_data';
Expand Down Expand Up @@ -76,7 +75,7 @@ describe('getAlertsQuery', () => {

// helper function to render the hook
const renderUseSummaryChartData = (props: Partial<UseAlertsQueryProps> = {}) =>
renderHook<PropsWithChildren<UseAlertsQueryProps>, ReturnType<UseAlerts>>(
renderHook(
() =>
useSummaryChartData({
aggregations: aggregations.severityAggregations,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import React from 'react';

import { useAlertsLocalStorage } from '.';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import type { FieldSpec } from '@kbn/data-plugin/common';

import type { GetAggregatableFields, UseInspectButtonParams } from './hooks';
Expand Down Expand Up @@ -120,7 +120,7 @@ describe('hooks', () => {
jest.clearAllMocks();
});
it('returns only aggregateable fields', () => {
const wrapper = ({ children }: { children: JSX.Element }) => (
const wrapper = ({ children }: React.PropsWithChildren) => (
<TestProviders>{children}</TestProviders>
);
const { result, unmount } = renderHook(() => useStackByFields(), { wrapper });
Expand All @@ -137,7 +137,7 @@ describe('hooks', () => {
browserFields: { base: mockBrowserFields.base },
});

const wrapper = ({ children }: { children: JSX.Element }) => (
const wrapper = ({ children }: React.PropsWithChildren) => (
<TestProviders>{children}</TestProviders>
);
const useLensCompatibleFields = true;
Expand All @@ -155,7 +155,7 @@ describe('hooks', () => {
browserFields: { nestedField: mockBrowserFields.nestedField },
});

const wrapper = ({ children }: { children: JSX.Element }) => (
const wrapper = ({ children }: React.PropsWithChildren) => (
<TestProviders>{children}</TestProviders>
);
const useLensCompatibleFields = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import type { EcsSecurityExtension as Ecs } from '@kbn/securitysolution-ecs';
import { useIsInvestigateInResolverActionEnabled } from './investigate_in_resolver';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { TestProviders } from '../../../../common/mock';

describe('InvestigateInResolverAction', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@

import React from 'react';
import { EuiContextMenu, EuiPopover } from '@elastic/eui';
import { act, renderHook } from '@testing-library/react-hooks';
import { render, screen } from '@testing-library/react';
import { render, screen, renderHook, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useAddToCaseActions } from './use_add_to_case_actions';
import { TestProviders } from '../../../../common/mock';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import type { UseAlertAssigneesActionsProps } from './use_alert_assignees_actions';
import { useAlertAssigneesActions } from './use_alert_assignees_actions';
import { useAlertsPrivileges } from '../../../containers/detection_engine/alerts/use_alerts_privileges';
import type { AlertTableContextMenuItem } from '../types';
import { render } from '@testing-library/react';
import { render, renderHook } from '@testing-library/react';
import React from 'react';
import type { EuiContextMenuPanelDescriptor } from '@elastic/eui';
import { EuiPopover, EuiContextMenu } from '@elastic/eui';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import type { UseAlertTagsActionsProps } from './use_alert_tags_actions';
import { useAlertTagsActions } from './use_alert_tags_actions';
import { useAlertsPrivileges } from '../../../containers/detection_engine/alerts/use_alerts_privileges';
import type { AlertTableContextMenuItem } from '../types';
import { render } from '@testing-library/react';
import { render, renderHook } from '@testing-library/react';
import React from 'react';
import type { EuiContextMenuPanelDescriptor } from '@elastic/eui';
import { EuiPopover, EuiContextMenu } from '@elastic/eui';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { renderHook, act } from '@testing-library/react-hooks';
import { fireEvent, render, waitFor } from '@testing-library/react';

import { fireEvent, render, waitFor, renderHook, act } from '@testing-library/react';
import { of } from 'rxjs';
import { TestProviders } from '../../../../common/mock';
import { useKibana } from '../../../../common/lib/kibana';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook, waitFor } from '@testing-library/react';
import { useKibana } from '../../../../common/lib/kibana';
import { createFindAlerts } from '../services/find_alerts';
import { useFetchAlerts, type UseAlertsQueryParams } from './use_fetch_alerts';
Expand Down Expand Up @@ -41,15 +41,14 @@ describe('useFetchAlerts', () => {
sort: [{ '@timestamp': 'desc' }],
};

const { result, waitFor } = renderHook(() => useFetchAlerts(params), {
const { result } = renderHook(() => useFetchAlerts(params), {
wrapper: createReactQueryWrapper(),
});

expect(result.current.loading).toBe(true);

await waitFor(() => !result.current.loading);
await waitFor(() => expect(result.current.loading).toBe(false));

expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(false);
expect(result.current.totalItemCount).toBe(10);
expect(result.current.data).toEqual(['alert1', 'alert2', 'alert3']);
Expand All @@ -70,13 +69,13 @@ describe('useFetchAlerts', () => {
sort: [{ '@timestamp': 'desc' }],
};

const { result, waitFor } = renderHook(() => useFetchAlerts(params), {
const { result } = renderHook(() => useFetchAlerts(params), {
wrapper: createReactQueryWrapper(),
});

expect(result.current.loading).toBe(true);

await waitFor(() => !result.current.loading);
await waitFor(() => expect(result.current.loading).toBe(false));

expect(result.current.loading).toBe(false);
expect(result.current.error).toBe(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useResponseActionsView } from './use_response_actions_view';
import { mockSearchHit } from '../../shared/mocks/mock_search_hit';
import { mockDataAsNestedObject } from '../../shared/mocks/mock_data_as_nested_object';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { useThreatIntelligenceDetails } from './use_threat_intelligence_details';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { SecurityPageName } from '@kbn/deeplinks-security';
import { useTimelineEventsDetails } from '../../../../timelines/containers/details';
import { useSourcererDataView } from '../../../../sourcerer/containers';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@

import type { ToggleReducerAction, UseAccordionStateValue } from './use_accordion_state';
import { useAccordionState, toggleReducer } from './use_accordion_state';
import type { RenderHookResult } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react-hooks';
import type { RenderHookResult } from '@testing-library/react';
import { renderHook } from '@testing-library/react';
import { FLYOUT_STORAGE_KEYS } from '../../shared/constants/local_storage';

const mockSet = jest.fn();

describe('useAccordionState', () => {
let hookResult: RenderHookResult<boolean, UseAccordionStateValue>;
let hookResult: RenderHookResult<UseAccordionStateValue, boolean>;

it('should return initial value', () => {
hookResult = renderHook((props: boolean) => useAccordionState(props), {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
* 2.0.
*/

import type { RenderHookResult } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react-hooks';
import type { RenderHookResult } from '@testing-library/react';
import { renderHook } from '@testing-library/react';
import type { UseAssistantParams, UseAssistantResult } from './use_assistant';
import { useAssistant } from './use_assistant';
import { mockDataFormattedForFieldBrowser } from '../../shared/mocks/mock_data_formatted_for_field_browser';
Expand All @@ -25,7 +25,7 @@ const renderUseAssistant = () =>
});

describe('useAssistant', () => {
let hookResult: RenderHookResult<UseAssistantParams, UseAssistantResult>;
let hookResult: RenderHookResult<UseAssistantResult, UseAssistantParams>;

it(`should return showAssistant true and a value for promptContextId`, () => {
jest.mocked(useAssistantAvailability).mockReturnValue({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@
* 2.0.
*/

import type { RenderHookResult } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react-hooks';
import type { RenderHookResult } from '@testing-library/react';
import { renderHook } from '@testing-library/react';
import type { UseExpandSectionParams } from './use_expand_section';
import { useExpandSection } from './use_expand_section';
import { useKibana } from '../../../../common/lib/kibana';

jest.mock('../../../../common/lib/kibana');

describe('useExpandSection', () => {
let hookResult: RenderHookResult<UseExpandSectionParams, boolean>;
let hookResult: RenderHookResult<boolean, UseExpandSectionParams>;

it('should return default value if nothing in localStorage', () => {
(useKibana as jest.Mock).mockReturnValue({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
* 2.0.
*/

import type { RenderHookResult } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react-hooks';
import type { RenderHookResult } from '@testing-library/react';
import { renderHook } from '@testing-library/react';
import type {
UseThreatIntelligenceParams,
UseThreatIntelligenceResult,
Expand Down Expand Up @@ -41,7 +41,7 @@ const dataFormattedForFieldBrowser = [
];

describe('useFetchThreatIntelligence', () => {
let hookResult: RenderHookResult<UseThreatIntelligenceParams, UseThreatIntelligenceResult>;
let hookResult: RenderHookResult<UseThreatIntelligenceResult, UseThreatIntelligenceParams>;

it('return render 1 match detected and 1 field enriched', () => {
(useInvestigationTimeEnrichment as jest.Mock).mockReturnValue({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { useFlyoutIsExpandable } from './use_flyout_is_expandable';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import type { EcsSecurityExtension as Ecs } from '@kbn/securitysolution-ecs';
import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features';

Expand Down
Loading

0 comments on commit a779c61

Please sign in to comment.