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

# Backport

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

<!--- 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-22T09:07:34Z","message":"[React18]
Migrate test suites to account for testing library upgrades
kibana-cloud-security-posture (#201159)\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.","sha":"b1eae2deed5016d68d84285d20a0751c2e4b6ed4","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:Cloud
Security","backport:prev-minor","React@18"],"title":"[React18] Migrate
test suites to account for testing library upgrades
kibana-cloud-security-posture","number":201159,"url":"https://github.com/elastic/kibana/pull/201159","mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
kibana-cloud-security-posture (#201159)\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.","sha":"b1eae2deed5016d68d84285d20a0751c2e4b6ed4"}},"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/201159","number":201159,"mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
kibana-cloud-security-posture (#201159)\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.","sha":"b1eae2deed5016d68d84285d20a0751c2e4b6ed4"}}]}] BACKPORT-->

Co-authored-by: Eyo O. Eyo <[email protected]>
  • Loading branch information
kibanamachine and eokoneyo authored Nov 22, 2024
1 parent ac4caed commit bf6d847
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 bf6d847

Please sign in to comment.