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

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.

##  Context

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.

### What to do next?
1. Review the changes in this PR.
2. If you think the changes are correct, approve the PR.

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

---------

Co-authored-by: Elastic Machine <[email protected]>
(cherry picked from commit 2ec351d)
  • Loading branch information
eokoneyo committed Nov 27, 2024
1 parent b36ff11 commit cb501ac
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 cb501ac

Please sign in to comment.