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-defend-workflows (#201174) (#201957)

# Backport

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

<!--- 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-11-27T12:11:20Z","message":"[React18]
Migrate test suites to account for testing library upgrades
security-defend-workflows (#201174)\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":"2ec351d99833bfe48fa25a10efc06c0ab66e33e6","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:Defend
Workflows","backport:prev-minor","React@18"],"title":"[React18] Migrate
test suites to account for testing library upgrades
security-defend-workflows","number":201174,"url":"https://github.com/elastic/kibana/pull/201174","mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
security-defend-workflows (#201174)\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":"2ec351d99833bfe48fa25a10efc06c0ab66e33e6"}},"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/201174","number":201174,"mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
security-defend-workflows (#201174)\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":"2ec351d99833bfe48fa25a10efc06c0ab66e33e6"}}]}]
BACKPORT-->

Co-authored-by: Eyo O. Eyo <[email protected]>
  • Loading branch information
kibanamachine and eokoneyo authored Nov 27, 2024
1 parent bfa5591 commit 317c955
Show file tree
Hide file tree
Showing 22 changed files with 232 additions and 184 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
import { useKibana } from '../../common/lib/kibana';
import { useIsOsqueryAvailableSimple } from './use_is_osquery_available_simple';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook, waitFor } from '@testing-library/react';
import { createStartServicesMock } from '@kbn/triggers-actions-ui-plugin/public/common/lib/kibana/kibana_react.mock';
import { OSQUERY_INTEGRATION_NAME } from '../../../common';
import { httpServiceMock } from '@kbn/core/public/mocks';
Expand Down Expand Up @@ -41,15 +41,13 @@ describe('UseIsOsqueryAvailableSimple', () => {
});
});
it('should expect response from API and return enabled flag', async () => {
const { result, waitForValueToChange } = renderHook(() =>
const { result } = renderHook(() =>
useIsOsqueryAvailableSimple({
agentId: '3242332',
})
);

expect(result.current).toBe(false);
await waitForValueToChange(() => result.current);

expect(result.current).toBe(true);
await waitFor(() => expect(result.current).toBe(true));
});
});
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 type React from 'react';
import { act } from '@testing-library/react';
import type { UseHostIsolationActionProps } from './use_host_isolation_action';
import { useHostIsolationAction } from './use_host_isolation_action';
import type { AppContextTestRender, UserPrivilegesMockSetter } from '../../../../mock/endpoint';
Expand All @@ -15,7 +16,6 @@ import type { AlertTableContextMenuItem } from '../../../../../detections/compon
import type { ResponseActionsApiCommandNames } from '../../../../../../common/endpoint/service/response_actions/constants';
import { agentStatusMocks } from '../../../../../../common/endpoint/service/response_actions/mocks/agent_status.mocks';
import { ISOLATE_HOST, UNISOLATE_HOST } from './translations';
import type React from 'react';
import {
HOST_ENDPOINT_UNENROLLED_TOOLTIP,
LOADING_ENDPOINT_DATA_TOOLTIP,
Expand Down Expand Up @@ -87,20 +87,22 @@ describe('useHostIsolationAction', () => {
});
}

const { result, waitForValueToChange } = render();
await waitForValueToChange(() => result.current);
const { result } = render();

expect(result.current).toEqual([
buildExpectedMenuItemResult({
...(command === 'unisolate' ? { name: UNISOLATE_HOST } : {}),
}),
]);
await appContextMock.waitFor(() =>
expect(result.current).toEqual([
buildExpectedMenuItemResult({
...(command === 'unisolate' ? { name: UNISOLATE_HOST } : {}),
}),
])
);
}
);

it('should call `closePopover` callback when menu item `onClick` is called', async () => {
const { result, waitForValueToChange } = render();
await waitForValueToChange(() => result.current);
const { result } = render();
await appContextMock.waitFor(() => expect(result.current[0].onClick).toBeDefined());

result.current[0].onClick!({} as unknown as React.MouseEvent);

expect(hookProps.closePopover).toHaveBeenCalled();
Expand Down Expand Up @@ -135,12 +137,14 @@ describe('useHostIsolationAction', () => {
it('should return disabled menu item while loading agent status', async () => {
const { result } = render();

expect(result.current).toEqual([
buildExpectedMenuItemResult({
disabled: true,
toolTipContent: LOADING_ENDPOINT_DATA_TOOLTIP,
}),
]);
await appContextMock.waitFor(() =>
expect(result.current).toEqual([
buildExpectedMenuItemResult({
disabled: true,
toolTipContent: LOADING_ENDPOINT_DATA_TOOLTIP,
}),
])
);
});

it.each(['endpoint', 'non-endpoint'])(
Expand All @@ -156,37 +160,51 @@ describe('useHostIsolationAction', () => {
if (type === 'non-endpoint') {
hookProps.detailsData = endpointAlertDataMock.generateSentinelOneAlertDetailsItemData();
}
const { result, waitForValueToChange } = render();
await waitForValueToChange(() => result.current);

expect(result.current).toEqual([
buildExpectedMenuItemResult({
disabled: true,
toolTipContent:
type === 'endpoint' ? HOST_ENDPOINT_UNENROLLED_TOOLTIP : NOT_FROM_ENDPOINT_HOST_TOOLTIP,
}),
]);
const { result } = render();
await appContextMock.waitFor(() =>
expect(result.current).toEqual([
buildExpectedMenuItemResult({
disabled: true,
toolTipContent:
type === 'endpoint'
? HOST_ENDPOINT_UNENROLLED_TOOLTIP
: NOT_FROM_ENDPOINT_HOST_TOOLTIP,
}),
])
);
}
);

it('should call isolate API when agent is currently NOT isolated', async () => {
const { result, waitForValueToChange } = render();
await waitForValueToChange(() => result.current);
const { result } = render();
await appContextMock.waitFor(() => expect(result.current[0].onClick).toBeDefined());
result.current[0].onClick!({} as unknown as React.MouseEvent);

expect(hookProps.onAddIsolationStatusClick).toHaveBeenCalledWith('isolateHost');
});

it('should call un-isolate API when agent is currently isolated', async () => {
apiMock.responseProvider.getAgentStatus.mockReturnValue(
agentStatusMocks.generateAgentStatusApiResponse({
data: { 'abfe4a35-d5b4-42a0-a539-bd054c791769': { isolated: true } },
})
);
const { result, waitForValueToChange } = render();
await waitForValueToChange(() => result.current);
result.current[0].onClick!({} as unknown as React.MouseEvent);
apiMock.responseProvider.getAgentStatus.mockImplementation(({ query }) => {
const agentId = (query!.agentIds as string[])[0];

return agentStatusMocks.generateAgentStatusApiResponse({
data: { [agentId]: { isolated: true } },
});
});

const { result } = render();

await appContextMock.waitFor(() => {
expect(apiMock.responseProvider.getAgentStatus).toHaveBeenCalled();
expect(result.current[0].onClick).toBeDefined();
});

act(() => {
result.current[0].onClick!({} as unknown as React.MouseEvent);
});

expect(hookProps.onAddIsolationStatusClick).toHaveBeenCalledWith('unisolateHost');
await appContextMock.waitFor(() =>
expect(hookProps.onAddIsolationStatusClick).toHaveBeenCalledWith('unisolateHost')
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ import type { AppContextTestRender } from '../../../../mock/endpoint';
import { createAppRootMockRenderer, endpointAlertDataMock } from '../../../../mock/endpoint';
import { HOST_METADATA_LIST_ROUTE } from '../../../../../../common/endpoint/constants';
import { endpointMetadataHttpMocks } from '../../../../../management/pages/endpoint_hosts/mocks';
import type { RenderHookResult } from '@testing-library/react-hooks/src/types';
import type { RenderHookResult } from '@testing-library/react';
import { waitFor, act } from '@testing-library/react';
import { createHttpFetchError } from '@kbn/core-http-browser-mocks';
import { HostStatus } from '../../../../../../common/endpoint/types';
import {
Expand Down Expand Up @@ -61,17 +62,14 @@ describe('use responder action data hooks', () => {

describe('useWithResponderActionDataFromAlert() hook', () => {
let renderHook: () => RenderHookResult<
UseWithResponderActionDataFromAlertProps,
ResponderActionData
ResponderActionData,
UseWithResponderActionDataFromAlertProps
>;
let alertDetailItemData: TimelineEventsDetailsItem[];

beforeEach(() => {
renderHook = () => {
return appContextMock.renderHook<
UseWithResponderActionDataFromAlertProps,
ResponderActionData
>(() =>
return appContextMock.renderHook(() =>
useWithResponderActionDataFromAlert({
eventData: alertDetailItemData,
onClick: onClickMock,
Expand All @@ -95,15 +93,19 @@ describe('use responder action data hooks', () => {
it('should call `onClick()` function prop when is pass to the hook', () => {
alertDetailItemData = endpointAlertDataMock.generateSentinelOneAlertDetailsItemData();
const { result } = renderHook();
result.current.handleResponseActionsClick();
act(() => {
result.current.handleResponseActionsClick();
});

expect(onClickMock).toHaveBeenCalled();
});

it('should NOT call `onClick` if the action is disabled', () => {
alertDetailItemData = endpointAlertDataMock.generateAlertDetailsItemDataForAgentType('foo');
const { result } = renderHook();
result.current.handleResponseActionsClick();
act(() => {
result.current.handleResponseActionsClick();
});

expect(onClickMock).not.toHaveBeenCalled();
});
Expand Down Expand Up @@ -169,8 +171,8 @@ describe('use responder action data hooks', () => {
});

it('should show action enabled if host metadata was retrieved and host is enrolled', async () => {
const { result, waitForValueToChange } = renderHook();
await waitForValueToChange(() => result.current.isDisabled);
const { result } = renderHook();
await waitFor(() => expect(result.current.isDisabled).toBe(false));

expect(result.current).toEqual(getExpectedResponderActionData());
});
Expand All @@ -181,8 +183,10 @@ describe('use responder action data hooks', () => {
statusCode: 404,
});
});
const { result, waitForValueToChange } = renderHook();
await waitForValueToChange(() => result.current.tooltip);

const { result } = renderHook();

await waitFor(() => expect(result.current.tooltip).not.toEqual('Loading'));

expect(result.current).toEqual(
getExpectedResponderActionData({
Expand All @@ -199,8 +203,8 @@ describe('use responder action data hooks', () => {
};
metadataApiMocks.responseProvider.metadataDetails.mockReturnValue(hostMetadata);

const { result, waitForValueToChange } = renderHook();
await waitForValueToChange(() => result.current.tooltip);
const { result } = renderHook();
await waitFor(() => expect(result.current.tooltip).not.toEqual('Loading'));

expect(result.current).toEqual(
getExpectedResponderActionData({
Expand All @@ -216,8 +220,8 @@ describe('use responder action data hooks', () => {
statusCode: 500,
});
});
const { result, waitForValueToChange } = renderHook();
await waitForValueToChange(() => result.current.tooltip);
const { result } = renderHook();
await waitFor(() => expect(result.current.tooltip).not.toEqual('Loading'));

expect(result.current).toEqual(
getExpectedResponderActionData({
Expand All @@ -231,7 +235,7 @@ describe('use responder action data hooks', () => {

describe('useResponderActionData() hook', () => {
let hookProps: UseResponderActionDataProps;
let renderHook: () => RenderHookResult<UseResponderActionDataProps, ResponderActionData>;
let renderHook: () => RenderHookResult<ResponderActionData, UseResponderActionDataProps>;

beforeEach(() => {
endpointMetadataHttpMocks(appContextMock.coreStart.http);
Expand All @@ -241,15 +245,13 @@ describe('use responder action data hooks', () => {
onClick: onClickMock,
};
renderHook = () => {
return appContextMock.renderHook<UseResponderActionDataProps, ResponderActionData>(() =>
useResponderActionData(hookProps)
);
return appContextMock.renderHook(() => useResponderActionData(hookProps));
};
});

it('should show action enabled when agentType is Endpoint and host is enabled', async () => {
const { result, waitForValueToChange } = renderHook();
await waitForValueToChange(() => result.current.isDisabled);
const { result } = renderHook();
await waitFor(() => expect(result.current.isDisabled).toBe(false));

expect(result.current).toEqual(getExpectedResponderActionData());
});
Expand All @@ -266,17 +268,24 @@ describe('use responder action data hooks', () => {
});

it('should call `onClick` prop when action is enabled', async () => {
const { result, waitForValueToChange } = renderHook();
await waitForValueToChange(() => result.current.isDisabled);
result.current.handleResponseActionsClick();
const { result } = renderHook();

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

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

expect(onClickMock).toHaveBeenCalled();
});

it('should not call `onCLick` prop when action is disabled', () => {
hookProps.agentType = 'sentinel_one';
const { result } = renderHook();
result.current.handleResponseActionsClick();

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

expect(onClickMock).not.toHaveBeenCalled();
});
Expand Down
Loading

0 comments on commit 317c955

Please sign in to comment.