Skip to content

Commit

Permalink
[8.x] [React18] Migrate test suites to account for testing library up…
Browse files Browse the repository at this point in the history
…grades security-solution (#201176) (#205265)

# Backport

This will backport the following commits from `main` to `8.x`:
- [[React18] Migrate test suites to account for testing library upgrades
security-solution
(#201176)](#201176)

<!--- Backport version: 9.4.3 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Eyo O.
Eyo","email":"[email protected]"},"sourceCommit":{"committedDate":"2024-12-30T14:23:51Z","message":"[React18]
Migrate test suites to account for testing library upgrades
security-solution (#201176)\n\nThis PR migrates test suites that use
`renderHook` from the library\r\n`@testing-library/react-hooks` to adopt
the equivalent and replacement\r\nof `renderHook` from the export that
is now available from\r\n`@testing-library/react`. This work is required
for the planned\r\nmigration to react18.\r\n\r\n## Context\r\n\r\nIn
this PR, usages of `waitForNextUpdate` that previously could
have\r\nbeen destructured from `renderHook` are now been replaced with
`waitFor`\r\nexported from `@testing-library/react`, furthermore
`waitFor`\r\nthat would also have been destructured from the same
renderHook result\r\nis now been replaced with `waitFor` from the export
of\r\n`@testing-library/react`.\r\n\r\n***Why is `waitFor` a sufficient
enough replacement for\r\n`waitForNextUpdate`, and better for testing
values subject to async\r\ncomputations?***\r\n\r\nWaitFor will retry
the provided callback if an error is returned, till\r\nthe configured
timeout elapses. By default the retry interval is `50ms`\r\nwith a
timeout value of `1000ms` that\r\neffectively translates to at least 20
retries for assertions placed\r\nwithin waitFor.
See\r\nhttps://testing-library.com/docs/dom-testing-library/api-async/#waitfor\r\nfor
more information.\r\nThis however means that for person's writing tests,
said person has to\r\nbe explicit about expectations that describe the
internal state of the\r\nhook being tested.\r\nThis implies checking for
instance when a react query hook is being\r\nrendered, there's an
assertion that said hook isn't loading anymore.\r\n\r\nIn this PR you'd
notice that this pattern has been adopted, with most\r\nexisting
assertions following an invocation of `waitForNextUpdate`
being\r\nplaced within a `waitFor`\r\ninvocation. In some cases the
replacement is simply a `waitFor(() => new\r\nPromise((resolve) =>
resolve(null)))` (many thanks to @kapral18, for\r\npoint out exactly why
this works),\r\nwhere this suffices the assertions that follow aren't
placed within a\r\nwaitFor so this PR doesn't get larger than it needs
to be.\r\n\r\nIt's also worth pointing out this PR might also contain
changes to test\r\nand application code to improve said existing
test.\r\n\r\n### What to do next?\r\n1. Review the changes in this
PR.\r\n2. If you think the changes are correct, approve the
PR.\r\n\r\n## Any questions?\r\nIf you have any questions or need help
with this PR, please leave\r\ncomments in this
PR.\r\n\r\n---------\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"f3d7fa7d122087b06eed098827d4c909b1ba90f2","branchLabelMapping":{"^v9.0.0$":"main","^v8.18.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","Team:
SecuritySolution","backport:prev-minor","React@18"],"title":"[React18]
Migrate test suites to account for testing library upgrades
security-solution","number":201176,"url":"https://github.com/elastic/kibana/pull/201176","mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
security-solution (#201176)\n\nThis PR migrates test suites that use
`renderHook` from the library\r\n`@testing-library/react-hooks` to adopt
the equivalent and replacement\r\nof `renderHook` from the export that
is now available from\r\n`@testing-library/react`. This work is required
for the planned\r\nmigration to react18.\r\n\r\n## Context\r\n\r\nIn
this PR, usages of `waitForNextUpdate` that previously could
have\r\nbeen destructured from `renderHook` are now been replaced with
`waitFor`\r\nexported from `@testing-library/react`, furthermore
`waitFor`\r\nthat would also have been destructured from the same
renderHook result\r\nis now been replaced with `waitFor` from the export
of\r\n`@testing-library/react`.\r\n\r\n***Why is `waitFor` a sufficient
enough replacement for\r\n`waitForNextUpdate`, and better for testing
values subject to async\r\ncomputations?***\r\n\r\nWaitFor will retry
the provided callback if an error is returned, till\r\nthe configured
timeout elapses. By default the retry interval is `50ms`\r\nwith a
timeout value of `1000ms` that\r\neffectively translates to at least 20
retries for assertions placed\r\nwithin waitFor.
See\r\nhttps://testing-library.com/docs/dom-testing-library/api-async/#waitfor\r\nfor
more information.\r\nThis however means that for person's writing tests,
said person has to\r\nbe explicit about expectations that describe the
internal state of the\r\nhook being tested.\r\nThis implies checking for
instance when a react query hook is being\r\nrendered, there's an
assertion that said hook isn't loading anymore.\r\n\r\nIn this PR you'd
notice that this pattern has been adopted, with most\r\nexisting
assertions following an invocation of `waitForNextUpdate`
being\r\nplaced within a `waitFor`\r\ninvocation. In some cases the
replacement is simply a `waitFor(() => new\r\nPromise((resolve) =>
resolve(null)))` (many thanks to @kapral18, for\r\npoint out exactly why
this works),\r\nwhere this suffices the assertions that follow aren't
placed within a\r\nwaitFor so this PR doesn't get larger than it needs
to be.\r\n\r\nIt's also worth pointing out this PR might also contain
changes to test\r\nand application code to improve said existing
test.\r\n\r\n### What to do next?\r\n1. Review the changes in this
PR.\r\n2. If you think the changes are correct, approve the
PR.\r\n\r\n## Any questions?\r\nIf you have any questions or need help
with this PR, please leave\r\ncomments in this
PR.\r\n\r\n---------\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"f3d7fa7d122087b06eed098827d4c909b1ba90f2"}},"sourceBranch":"main","suggestedTargetBranches":[],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","branchLabelMappingKey":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/201176","number":201176,"mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
security-solution (#201176)\n\nThis PR migrates test suites that use
`renderHook` from the library\r\n`@testing-library/react-hooks` to adopt
the equivalent and replacement\r\nof `renderHook` from the export that
is now available from\r\n`@testing-library/react`. This work is required
for the planned\r\nmigration to react18.\r\n\r\n## Context\r\n\r\nIn
this PR, usages of `waitForNextUpdate` that previously could
have\r\nbeen destructured from `renderHook` are now been replaced with
`waitFor`\r\nexported from `@testing-library/react`, furthermore
`waitFor`\r\nthat would also have been destructured from the same
renderHook result\r\nis now been replaced with `waitFor` from the export
of\r\n`@testing-library/react`.\r\n\r\n***Why is `waitFor` a sufficient
enough replacement for\r\n`waitForNextUpdate`, and better for testing
values subject to async\r\ncomputations?***\r\n\r\nWaitFor will retry
the provided callback if an error is returned, till\r\nthe configured
timeout elapses. By default the retry interval is `50ms`\r\nwith a
timeout value of `1000ms` that\r\neffectively translates to at least 20
retries for assertions placed\r\nwithin waitFor.
See\r\nhttps://testing-library.com/docs/dom-testing-library/api-async/#waitfor\r\nfor
more information.\r\nThis however means that for person's writing tests,
said person has to\r\nbe explicit about expectations that describe the
internal state of the\r\nhook being tested.\r\nThis implies checking for
instance when a react query hook is being\r\nrendered, there's an
assertion that said hook isn't loading anymore.\r\n\r\nIn this PR you'd
notice that this pattern has been adopted, with most\r\nexisting
assertions following an invocation of `waitForNextUpdate`
being\r\nplaced within a `waitFor`\r\ninvocation. In some cases the
replacement is simply a `waitFor(() => new\r\nPromise((resolve) =>
resolve(null)))` (many thanks to @kapral18, for\r\npoint out exactly why
this works),\r\nwhere this suffices the assertions that follow aren't
placed within a\r\nwaitFor so this PR doesn't get larger than it needs
to be.\r\n\r\nIt's also worth pointing out this PR might also contain
changes to test\r\nand application code to improve said existing
test.\r\n\r\n### What to do next?\r\n1. Review the changes in this
PR.\r\n2. If you think the changes are correct, approve the
PR.\r\n\r\n## Any questions?\r\nIf you have any questions or need help
with this PR, please leave\r\ncomments in this
PR.\r\n\r\n---------\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"f3d7fa7d122087b06eed098827d4c909b1ba90f2"}}]}]
BACKPORT-->

Co-authored-by: Eyo O. Eyo <[email protected]>
  • Loading branch information
kibanamachine and eokoneyo authored Dec 30, 2024
1 parent 36edd99 commit f14e250
Show file tree
Hide file tree
Showing 93 changed files with 666 additions and 825 deletions.
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 { usePanelSideNavItems } from './use_panel_side_nav_items';
import { SecurityPageName } from '@kbn/security-solution-navigation';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,10 @@
* 2.0.
*/

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

import { mockQuery, mockAlertCountByRuleResult, parsedAlertCountByRuleResult } from './mock_data';
import type {
UseAlertCountByRuleByStatus,
UseAlertCountByRuleByStatusProps,
} from './use_alert_count_by_rule_by_status';
import type { UseAlertCountByRuleByStatusProps } from './use_alert_count_by_rule_by_status';
import { useAlertCountByRuleByStatus } from './use_alert_count_by_rule_by_status';

const dateNow = new Date('2022-04-15T12:00:00.000Z').valueOf();
Expand Down Expand Up @@ -53,7 +50,7 @@ jest.mock('../../../detections/containers/detection_engine/alerts/use_signal_ind
const renderUseAlertCountByRuleByStatus = (
overrides: Partial<UseAlertCountByRuleByStatusProps> = {}
) =>
renderHook<UseAlertCountByRuleByStatusProps, ReturnType<UseAlertCountByRuleByStatus>>(() =>
renderHook(() =>
useAlertCountByRuleByStatus({
skip: false,
field: 'test_field',
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 { TestProviders } from '../../../../mock';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { createSearchSourceMock } from '@kbn/data-plugin/public/mocks';
import { discoverPluginMock } from '@kbn/discover-plugin/public/mocks';
import { dataViewMock } from '@kbn/discover-utils/src/__mocks__';
import type { SavedSearch } from '@kbn/saved-search-plugin/common';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, act, renderHook } from '@testing-library/react';
import { createMockStore, mockGlobalState, TestProviders } from '../../mock';
import { useDiscoverInTimelineActions } from './use_discover_in_timeline_actions';
import type { Filter } from '@kbn/es-query';
Expand All @@ -20,9 +20,6 @@ import * as timelineActions from '../../../timelines/store/actions';
import type { ComponentType, FC, PropsWithChildren } from 'react';
import React from 'react';
import type { DataView } from '@kbn/data-views-plugin/common';
import TestRenderer from 'react-test-renderer';

const { act } = TestRenderer;

let mockDiscoverStateContainerRef = {
current: discoverPluginMock.getDiscoverStateMock({}),
Expand Down Expand Up @@ -148,7 +145,7 @@ describe('useDiscoverInTimelineActions', () => {
});
describe('getAppStateFromSavedSearch', () => {
it('should reach out to discover to convert app state from saved search', async () => {
const { result, waitFor } = renderTestHook();
const { result } = renderTestHook();
const { appState } = result.current.getAppStateFromSavedSearch(savedSearchMock);
await waitFor(() => {
expect(appState).toMatchObject(
Expand Down Expand Up @@ -178,15 +175,15 @@ describe('useDiscoverInTimelineActions', () => {

describe('resetDiscoverAppState', () => {
it('should reset Discover AppState to a default state', async () => {
const { result, waitFor } = renderTestHook();
const { result } = renderTestHook();
await result.current.resetDiscoverAppState();
await waitFor(() => {
const appState = mockDiscoverStateContainerRef.current.appState.getState();
expect(appState).toMatchObject(result.current.defaultDiscoverAppState);
});
});
it('should reset Discover time to a default state', async () => {
const { result, waitFor } = renderTestHook();
const { result } = renderTestHook();
await result.current.resetDiscoverAppState();
await waitFor(() => {
const globalState = mockDiscoverStateContainerRef.current.globalState.get();
Expand All @@ -197,6 +194,15 @@ describe('useDiscoverInTimelineActions', () => {
describe('updateSavedSearch', () => {
it('should add defaults to the savedSearch before updating saved search', async () => {
const { result } = renderTestHook();

await waitFor(() =>
expect(result.current).toEqual(
expect.objectContaining({
updateSavedSearch: expect.any(Function),
})
)
);

await act(async () => {
await result.current.updateSavedSearch(savedSearchMock, TimelineId.active);
});
Expand All @@ -216,6 +222,7 @@ describe('useDiscoverInTimelineActions', () => {
})
);
});

it('should initialize saved search when it is not set on the timeline model yet', async () => {
const localMockState: State = {
...mockGlobalState,
Expand All @@ -235,6 +242,13 @@ describe('useDiscoverInTimelineActions', () => {

const LocalTestProvider = getTestProviderWithCustomState(localMockState);
const { result } = renderTestHook(LocalTestProvider);
await waitFor(() =>
expect(result.current).toEqual(
expect.objectContaining({
updateSavedSearch: expect.any(Function),
})
)
);
await act(async () => {
await result.current.updateSavedSearch(savedSearchMock, TimelineId.active);
});
Expand Down Expand Up @@ -269,6 +283,13 @@ describe('useDiscoverInTimelineActions', () => {

const LocalTestProvider = getTestProviderWithCustomState(localMockState);
const { result } = renderTestHook(LocalTestProvider);
await waitFor(() =>
expect(result.current).toEqual(
expect.objectContaining({
updateSavedSearch: expect.any(Function),
})
)
);
await act(async () => {
await result.current.updateSavedSearch(changedSavedSearchMock, TimelineId.active);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

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

import { APP_ID } from '../../../../common/constants';
import { DEFAULT_STACK_BY_FIELD } from '../../../detections/components/alerts_kpis/common/config';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks';

import { act, waitFor, renderHook } from '@testing-library/react';
import { TestProviders } from '../../../mock';
import { useAggregatedAnomaliesByJob, AnomalyEntity } from './use_anomalies_search';

Expand Down Expand Up @@ -70,37 +71,27 @@ describe('useAggregatedAnomaliesByJob', () => {
});

it('refetch calls useSecurityJobs().refetch', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook(
() => useAggregatedAnomaliesByJob({ skip: false, from, to }),
{
wrapper: TestProviders,
}
);

await waitForNextUpdate();
const { result } = renderHook(() => useAggregatedAnomaliesByJob({ skip: false, from, to }), {
wrapper: TestProviders,
});

act(() => {
result.current.refetch();
});

expect(useSecurityJobsRefetch).toHaveBeenCalled();
});

it('returns formated data', async () => {
await act(async () => {
const jobCount = { key: jobId, doc_count: 99 };
mockAnomaliesSearch.mockResolvedValue({
aggregations: { number_of_anomalies: { buckets: [jobCount] } },
});
const { result, waitForNextUpdate } = renderHook(
() => useAggregatedAnomaliesByJob({ skip: false, from, to }),
{
wrapper: TestProviders,
}
);
await waitForNextUpdate();
await waitForNextUpdate();
const jobCount = { key: jobId, doc_count: 99 };
mockAnomaliesSearch.mockResolvedValue({
aggregations: { number_of_anomalies: { buckets: [jobCount] } },
});
const { result } = renderHook(() => useAggregatedAnomaliesByJob({ skip: false, from, to }), {
wrapper: TestProviders,
});

await waitFor(() =>
expect(result.current.data).toEqual(
expect.arrayContaining([
{
Expand All @@ -110,55 +101,50 @@ describe('useAggregatedAnomaliesByJob', () => {
entity: AnomalyEntity.Host,
},
])
);
});
)
);
});

it('returns jobs sorted by name', async () => {
await act(async () => {
const firstJobId = 'v3_windows_anomalous_script';
const secondJobId = 'auth_rare_source_ip_for_a_user';
const fistJobCount = { key: firstJobId, doc_count: 99 };
const secondJobCount = { key: secondJobId, doc_count: 99 };
const firstJobSecurityName = '0000001';
const secondJobSecurityName = '0000002';
const firstJob = {
id: firstJobId,
jobState: 'started',
datafeedState: 'started',
customSettings: {
security_app_display_name: firstJobSecurityName,
},
};
const secondJob = {
id: secondJobId,
jobState: 'started',
datafeedState: 'started',
customSettings: {
security_app_display_name: secondJobSecurityName,
},
};

mockAnomaliesSearch.mockResolvedValue({
aggregations: { number_of_anomalies: { buckets: [fistJobCount, secondJobCount] } },
});
const firstJobId = 'v3_windows_anomalous_script';
const secondJobId = 'auth_rare_source_ip_for_a_user';
const fistJobCount = { key: firstJobId, doc_count: 99 };
const secondJobCount = { key: secondJobId, doc_count: 99 };
const firstJobSecurityName = '0000001';
const secondJobSecurityName = '0000002';
const firstJob = {
id: firstJobId,
jobState: 'started',
datafeedState: 'started',
customSettings: {
security_app_display_name: firstJobSecurityName,
},
};
const secondJob = {
id: secondJobId,
jobState: 'started',
datafeedState: 'started',
customSettings: {
security_app_display_name: secondJobSecurityName,
},
};

mockAnomaliesSearch.mockResolvedValue({
aggregations: { number_of_anomalies: { buckets: [fistJobCount, secondJobCount] } },
});

mockUseSecurityJobs.mockReturnValue({
loading: false,
isMlAdmin: true,
jobs: [firstJob, secondJob],
refetch: useSecurityJobsRefetch,
});
mockUseSecurityJobs.mockReturnValue({
loading: false,
isMlAdmin: true,
jobs: [firstJob, secondJob],
refetch: useSecurityJobsRefetch,
});

const { result, waitForNextUpdate } = renderHook(
() => useAggregatedAnomaliesByJob({ skip: false, from, to }),
{
wrapper: TestProviders,
}
);
await waitForNextUpdate();
await waitForNextUpdate();
const { result } = renderHook(() => useAggregatedAnomaliesByJob({ skip: false, from, to }), {
wrapper: TestProviders,
});

await waitFor(() => {
const names = result.current.data.map(({ name }) => name);

expect(names[0]).toEqual(firstJobSecurityName);
Expand All @@ -167,18 +153,11 @@ describe('useAggregatedAnomaliesByJob', () => {
});

it('does not throw error when aggregations is undefined', async () => {
await act(async () => {
mockAnomaliesSearch.mockResolvedValue({});
const { waitForNextUpdate } = renderHook(
() => useAggregatedAnomaliesByJob({ skip: false, from, to }),
{
wrapper: TestProviders,
}
);
await waitForNextUpdate();
await waitForNextUpdate();

expect(mockAddToastError).not.toBeCalled();
mockAnomaliesSearch.mockResolvedValue({});
renderHook(() => useAggregatedAnomaliesByJob({ skip: false, from, to }), {
wrapper: TestProviders,
});

await waitFor(() => expect(mockAddToastError).not.toBeCalled());
});
});
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 { waitFor, renderHook } from '@testing-library/react';

import { hasMlUserPermissions } from '../../../../../common/machine_learning/has_ml_user_permissions';
import { hasMlLicense } from '../../../../../common/machine_learning/has_ml_license';
Expand Down Expand Up @@ -38,12 +38,12 @@ describe('useInstalledSecurityJobs', () => {
});

it('returns jobs and permissions', async () => {
const { result, waitForNextUpdate } = renderHook(() => useInstalledSecurityJobs(), {
const { result } = renderHook(() => useInstalledSecurityJobs(), {
wrapper: TestProviders,
});
await waitForNextUpdate();

expect(result.current.jobs).toHaveLength(3);
await waitFor(() => expect(result.current.jobs).toHaveLength(3));

expect(result.current.jobs).toEqual(
expect.arrayContaining([
{
Expand Down Expand Up @@ -71,25 +71,26 @@ describe('useInstalledSecurityJobs', () => {
});

it('filters out non-security jobs', async () => {
const { result, waitForNextUpdate } = renderHook(() => useInstalledSecurityJobs(), {
const { result } = renderHook(() => useInstalledSecurityJobs(), {
wrapper: TestProviders,
});
await waitForNextUpdate();
await waitFor(() => expect(result.current.jobs.length).toBeGreaterThan(0));

expect(result.current.jobs.length).toBeGreaterThan(0);
expect(result.current.jobs.every(isSecurityJob)).toEqual(true);
});

it('renders a toast error if the ML call fails', async () => {
(getJobsSummary as jest.Mock).mockRejectedValue('whoops');
const { waitForNextUpdate } = renderHook(() => useInstalledSecurityJobs(), {

renderHook(() => useInstalledSecurityJobs(), {
wrapper: TestProviders,
});
await waitForNextUpdate();

expect(appToastsMock.addError).toHaveBeenCalledWith('whoops', {
title: 'Security job fetch failure',
});
await waitFor(() =>
expect(appToastsMock.addError).toHaveBeenCalledWith('whoops', {
title: 'Security job fetch failure',
})
);
});
});

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 { TestProviders } from '../../../mock';
import { buildMockJobsSummary, getJobsSummaryResponseMock } from '../../ml_popover/api.mock';
import { useInstalledSecurityJobs } from './use_installed_security_jobs';
Expand Down
Loading

0 comments on commit f14e250

Please sign in to comment.