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
… kibana-cloud-security-posture (elastic#201159)

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.
  • Loading branch information
eokoneyo authored and CAWilson94 committed Dec 12, 2024
1 parent 1e6b21a commit 142d1cd
Show file tree
Hide file tree
Showing 7 changed files with 51 additions and 50 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook, act } from '@testing-library/react-hooks/dom';
import { renderHook, act } from '@testing-library/react';
import { useNavigateVulnerabilities, useNavigateFindings } from './use_navigate_findings';
import { useHistory } from 'react-router-dom';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { useBenchmarkDynamicValues } from './use_benchmark_dynamic_values';
import { renderHook } from '@testing-library/react-hooks/dom';
import { renderHook } from '@testing-library/react';
import type { BenchmarksCisId } from '@kbn/cloud-security-posture-common';
import { useCspIntegrationLink } from '../navigation/use_csp_integration_link';

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

import { renderHook, act } from '@testing-library/react-hooks/dom';
import { renderHook, act } from '@testing-library/react';
import { useUrlQuery } from './use_url_query';
import { useLocation, useHistory } from 'react-router-dom';
import { encodeQuery } from '@kbn/cloud-security-posture';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

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

import { SetupTechnology } from '@kbn/fleet-plugin/public';
import { AgentPolicy, NewPackagePolicyInput } from '@kbn/fleet-plugin/common';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/
import React from 'react';
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import type { RuleStateAttributes } from '@kbn/cloud-security-posture-common/schema/rules/v4';
Expand Down Expand Up @@ -87,7 +87,7 @@ describe('use_change_csp_rule_state', () => {
const appMockRender = testWrapper();
const httpPostSpy = jest.spyOn(useKibana().services.http!, 'post');

const { result, waitForNextUpdate } = await renderHook(() => useChangeCspRuleState(), {
const { result } = await renderHook(() => useChangeCspRuleState(), {
wrapper: appMockRender.wrapper,
});

Expand All @@ -107,22 +107,22 @@ describe('use_change_csp_rule_state', () => {
result.current.mutate(mockRuleStateUpdateRequest);
});

await waitForNextUpdate();

expect(httpPostSpy).toHaveBeenCalledWith(CSP_BENCHMARK_RULES_BULK_ACTION_ROUTE_PATH, {
version: '1',
body: JSON.stringify({
action: 'mute',
rules: [
{
benchmark_id: 'benchmark_id',
benchmark_version: 'benchmark_version',
rule_number: '1',
rule_id: 'rule_1',
},
],
}),
});
await waitFor(() =>
expect(httpPostSpy).toHaveBeenCalledWith(CSP_BENCHMARK_RULES_BULK_ACTION_ROUTE_PATH, {
version: '1',
body: JSON.stringify({
action: 'mute',
rules: [
{
benchmark_id: 'benchmark_id',
benchmark_version: 'benchmark_version',
rule_number: '1',
rule_id: 'rule_1',
},
],
}),
})
);
});

it('should cancel queries and update query data onMutate', async () => {
Expand All @@ -131,7 +131,7 @@ describe('use_change_csp_rule_state', () => {
const queryClientGetSpy = jest.spyOn(appMockRender.queryClient, 'getQueryData');
const mockSetQueryDataSpy = jest.spyOn(appMockRender.queryClient, 'setQueryData');

const { result, waitForNextUpdate } = await renderHook(() => useChangeCspRuleState(), {
const { result } = await renderHook(() => useChangeCspRuleState(), {
wrapper: appMockRender.wrapper,
});

Expand All @@ -151,24 +151,24 @@ describe('use_change_csp_rule_state', () => {
result.current.mutate(mockRuleStateUpdateRequest);
});

await waitForNextUpdate();

const expectedMutatedRules = {
...initialRules,
rule_1: { ...initialRules.rule_1, muted: true },
};
await waitFor(() => {
const expectedMutatedRules = {
...initialRules,
rule_1: { ...initialRules.rule_1, muted: true },
};

expect(queryClientSpy).toHaveBeenCalled();
expect(queryClientGetSpy).toHaveBeenCalled();
expect(mockSetQueryDataSpy).toHaveBeenCalled();
expect(mockSetQueryDataSpy).toHaveReturnedWith(expectedMutatedRules);
expect(queryClientSpy).toHaveBeenCalled();
expect(queryClientGetSpy).toHaveBeenCalled();
expect(mockSetQueryDataSpy).toHaveBeenCalled();
expect(mockSetQueryDataSpy).toHaveReturnedWith(expectedMutatedRules);
});
});

it('should invalidate queries onSettled', async () => {
const appMockRender = testWrapper();
const mockInvalidateQueriesSpy = jest.spyOn(appMockRender.queryClient, 'invalidateQueries');

const { result, waitForNextUpdate } = await renderHook(() => useChangeCspRuleState(), {
const { result } = await renderHook(() => useChangeCspRuleState(), {
wrapper: appMockRender.wrapper,
});

Expand All @@ -188,19 +188,19 @@ describe('use_change_csp_rule_state', () => {
result.current.mutate(mockRuleStateUpdateRequest);
});

await waitForNextUpdate();

expect(mockInvalidateQueriesSpy).toHaveBeenCalledWith(BENCHMARK_INTEGRATION_QUERY_KEY_V2);
expect(mockInvalidateQueriesSpy).toHaveBeenCalledWith(CSPM_STATS_QUERY_KEY);
expect(mockInvalidateQueriesSpy).toHaveBeenCalledWith(KSPM_STATS_QUERY_KEY);
expect(mockInvalidateQueriesSpy).toHaveBeenCalledWith(CSP_RULES_STATES_QUERY_KEY);
await waitFor(() => {
expect(mockInvalidateQueriesSpy).toHaveBeenCalledWith(BENCHMARK_INTEGRATION_QUERY_KEY_V2);
expect(mockInvalidateQueriesSpy).toHaveBeenCalledWith(CSPM_STATS_QUERY_KEY);
expect(mockInvalidateQueriesSpy).toHaveBeenCalledWith(KSPM_STATS_QUERY_KEY);
expect(mockInvalidateQueriesSpy).toHaveBeenCalledWith(CSP_RULES_STATES_QUERY_KEY);
});
});

it('should restore previous query data onError', async () => {
const appMockRender = testWrapper();
const mockSetQueryDataSpy = jest.spyOn(appMockRender.queryClient, 'setQueryData');

const { result, waitForNextUpdate } = await renderHook(() => useChangeCspRuleState(), {
const { result } = await renderHook(() => useChangeCspRuleState(), {
wrapper: appMockRender.wrapper,
});

Expand All @@ -221,13 +221,13 @@ describe('use_change_csp_rule_state', () => {
result.current.mutate(mockRuleStateUpdateRequest);
});

await waitForNextUpdate();

expect(mockSetQueryDataSpy).toHaveBeenCalled();
expect(mockSetQueryDataSpy).toHaveReturnedWith(initialRules);
await waitFor(() => {
expect(mockSetQueryDataSpy).toHaveBeenCalled();
expect(mockSetQueryDataSpy).toHaveReturnedWith(initialRules);
});
});

it('creates the new set of cache rules in a muted state when calling createRulesWithUpdatedState', async () => {
it('creates the new set of cache rules in a muted state when calling createRulesWithUpdatedState', () => {
const request: RuleStateUpdateRequest = {
newState: 'mute',
ruleIds: [
Expand Down Expand Up @@ -267,7 +267,7 @@ describe('use_change_csp_rule_state', () => {
expect(newRulesState).toEqual({ ...initialRules, ...updateRules });
});

it('creates the new cache with rules in a unmute state', async () => {
it('creates the new cache with rules in a unmute state', () => {
const initialMutedRules: Record<string, RuleStateAttributes> = {
rule_1: {
benchmark_id: 'benchmark_id',
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 { renderHook, act } from '@testing-library/react-hooks';

import { renderHook, act } from '@testing-library/react';
import { sessionViewIOEventsMock } from '../../../common/mocks/responses/session_view_io_events.mock';
import { useIOLines, useXtermPlayer, XtermPlayerDeps } from './hooks';
import type { ProcessEventsPage } from '../../../common';
Expand All @@ -31,7 +32,7 @@ describe('TTYPlayer/hooks', () => {

// test memoization
let last = result.current.lines;
rerender();
rerender({ pages: initial });
expect(result.current.lines === last).toBeTruthy();
last = result.current.lines;
rerender({ pages: [...initial] });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { AppContextTestRender, createAppRootMockRenderer } from '../../test';
import { sessionViewIOEventsMock } from '../../../common/mocks/responses/session_view_io_events.mock';
Expand Down

0 comments on commit 142d1cd

Please sign in to comment.