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 fleet (#201166) (#201323)

# Backport

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

<!--- 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:06:17Z","message":"[React18]
Migrate test suites to account for testing library upgrades fleet
(#201166)\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":"4fbcf073678f13ba65d1f58120e897aceb5fa1ab","branchLabelMapping":{"^v9.0.0$":"main","^v8.18.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","Team:Fleet","v9.0.0","backport:prev-minor","React@18"],"title":"[React18]
Migrate test suites to account for testing library upgrades
fleet","number":201166,"url":"https://github.com/elastic/kibana/pull/201166","mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades fleet
(#201166)\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":"4fbcf073678f13ba65d1f58120e897aceb5fa1ab"}},"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/201166","number":201166,"mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades fleet
(#201166)\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":"4fbcf073678f13ba65d1f58120e897aceb5fa1ab"}}]}] BACKPORT-->

Co-authored-by: Eyo O. Eyo <[email protected]>
  • Loading branch information
kibanamachine and eokoneyo authored Nov 22, 2024
1 parent 8a32e35 commit ac4caed
Show file tree
Hide file tree
Showing 23 changed files with 170 additions and 196 deletions.
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 } from '@testing-library/react-hooks';

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

import type { DataStream } from '../types';
import * as useLocatorModule from '../../../hooks/use_locator';
Expand All @@ -29,12 +30,12 @@ describe('useApmServiceHref hook', () => {
package: 'elastic_agent',
} as DataStream;

const { result, waitForNextUpdate } = renderHook(() => useAPMServiceDetailHref(datastream));

await waitForNextUpdate();
const { result } = renderHook(() => useAPMServiceDetailHref(datastream));

expect(result.current).toMatchObject({ isSuccessful: true, href: undefined });
expect(apmLocatorMock).not.toBeCalled();
await waitFor(() => {
expect(result.current).toMatchObject({ isSuccessful: true, href: undefined });
expect(apmLocatorMock).not.toBeCalled();
});
});

const testCases = [
Expand Down Expand Up @@ -83,12 +84,12 @@ describe('useApmServiceHref hook', () => {
it.each(testCases)(
'it passes the correct params to apm locator for %s',
async (datastream, locatorParams) => {
const { result, waitForNextUpdate } = renderHook(() => useAPMServiceDetailHref(datastream));

await waitForNextUpdate();
const { result } = renderHook(() => useAPMServiceDetailHref(datastream));

expect(result.current).toMatchObject({ isSuccessful: true, href: '' });
expect(apmLocatorMock).toBeCalledWith(expect.objectContaining(locatorParams));
await waitFor(() => {
expect(result.current).toMatchObject({ isSuccessful: true, href: '' });
expect(apmLocatorMock).toBeCalledWith(expect.objectContaining(locatorParams));
});
}
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
* 2.0.
*/

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

import { createFleetTestRendererMock } from '../../../../../../mock';
import type { MockedFleetStartServices } from '../../../../../../mock';
import { useLicense } from '../../../../../../hooks/use_license';
Expand Down Expand Up @@ -189,12 +191,10 @@ describe('useOutputOptions', () => {
hasAtLeast: () => true,
} as unknown as LicenseService);
mockApiCallsWithOutputs(testRenderer.startServices.http);
const { result, waitForNextUpdate } = testRenderer.renderHook(() =>
useOutputOptions({} as AgentPolicy)
);
const { result } = testRenderer.renderHook(() => useOutputOptions({} as AgentPolicy));
expect(result.current.isLoading).toBeTruthy();

await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(result.current.dataOutputOptions).toMatchInlineSnapshot(`
Array [
Object {
Expand Down Expand Up @@ -317,12 +317,10 @@ describe('useOutputOptions', () => {
hasAtLeast: () => false,
} as unknown as LicenseService);
mockApiCallsWithOutputs(testRenderer.startServices.http);
const { result, waitForNextUpdate } = testRenderer.renderHook(() =>
useOutputOptions({} as AgentPolicy)
);
const { result } = testRenderer.renderHook(() => useOutputOptions({} as AgentPolicy));
expect(result.current.isLoading).toBeTruthy();

await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(result.current.dataOutputOptions).toMatchInlineSnapshot(`
Array [
Object {
Expand Down Expand Up @@ -445,12 +443,10 @@ describe('useOutputOptions', () => {
hasAtLeast: () => true,
} as unknown as LicenseService);
mockApiCallsWithLogstashOutputs(testRenderer.startServices.http);
const { result, waitForNextUpdate } = testRenderer.renderHook(() =>
useOutputOptions({} as AgentPolicy)
);
const { result } = testRenderer.renderHook(() => useOutputOptions({} as AgentPolicy));
expect(result.current.isLoading).toBeTruthy();

await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(result.current.dataOutputOptions).toMatchInlineSnapshot(`
Array [
Object {
Expand Down Expand Up @@ -497,7 +493,7 @@ describe('useOutputOptions', () => {
hasAtLeast: () => true,
} as unknown as LicenseService);
mockApiCallsWithLogstashOutputs(testRenderer.startServices.http);
const { result, waitForNextUpdate } = testRenderer.renderHook(() =>
const { result } = testRenderer.renderHook(() =>
useOutputOptions({
package_policies: [
{
Expand All @@ -510,7 +506,7 @@ describe('useOutputOptions', () => {
);
expect(result.current.isLoading).toBeTruthy();

await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(result.current.dataOutputOptions).toMatchInlineSnapshot(`
Array [
Object {
Expand Down Expand Up @@ -601,12 +597,10 @@ describe('useOutputOptions', () => {
hasAtLeast: () => true,
} as unknown as LicenseService);
mockApiCallsWithRemoteESOutputs(testRenderer.startServices.http);
const { result, waitForNextUpdate } = testRenderer.renderHook(() =>
useOutputOptions({} as AgentPolicy)
);
const { result } = testRenderer.renderHook(() => useOutputOptions({} as AgentPolicy));
expect(result.current.isLoading).toBeTruthy();

await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(result.current.dataOutputOptions.length).toEqual(2);
expect(result.current.dataOutputOptions[1].value).toEqual('remote1');
expect(result.current.monitoringOutputOptions.length).toEqual(2);
Expand All @@ -619,12 +613,10 @@ describe('useOutputOptions', () => {
hasAtLeast: () => true,
} as unknown as LicenseService);
mockApiCallsWithInternalOutputs(testRenderer.startServices.http);
const { result, waitForNextUpdate } = testRenderer.renderHook(() =>
useOutputOptions({} as AgentPolicy)
);
const { result } = testRenderer.renderHook(() => useOutputOptions({} as AgentPolicy));
expect(result.current.isLoading).toBeTruthy();

await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(result.current.dataOutputOptions).toMatchInlineSnapshot(`
Array [
Object {
Expand Down Expand Up @@ -670,12 +662,10 @@ describe('useFleetServerHostsOptions', () => {
it('should not enable internal fleet server hosts', async () => {
const testRenderer = createFleetTestRendererMock();
mockApiCallsWithInternalFleetServerHost(testRenderer.startServices.http);
const { result, waitForNextUpdate } = testRenderer.renderHook(() =>
useFleetServerHostsOptions({} as AgentPolicy)
);
const { result } = testRenderer.renderHook(() => useFleetServerHostsOptions({} as AgentPolicy));
expect(result.current.isLoading).toBeTruthy();

await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(result.current.fleetServerHostsOptions).toMatchInlineSnapshot(`
Array [
Object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
* 2.0.
*/

import { act } from '@testing-library/react-hooks';
import type { RenderHookResult } from '@testing-library/react-hooks';
import type { RenderHookResult } from '@testing-library/react';
import { act, waitFor } from '@testing-library/react';

import type { TestRenderer } from '../../../../../../../mock';
import { createFleetTestRendererMock } from '../../../../../../../mock';
Expand Down Expand Up @@ -71,11 +71,11 @@ describe('useOnSubmit', () => {

let testRenderer: TestRenderer;
let renderResult: RenderHookResult<
Parameters<typeof useOnSubmit>,
ReturnType<typeof useOnSubmit>
ReturnType<typeof useOnSubmit>,
Parameters<typeof useOnSubmit>
>;
const render = ({ isUpdate } = { isUpdate: false }) =>
(renderResult = testRenderer.renderHook(() =>
const render = async ({ isUpdate } = { isUpdate: false }) => {
renderResult = testRenderer.renderHook(() =>
useOnSubmit({
agentCount: 0,
packageInfo,
Expand All @@ -85,7 +85,12 @@ describe('useOnSubmit', () => {
queryParamsPolicyId: undefined,
hasFleetAddAgentsPrivileges: true,
})
));
);

await waitFor(() => new Promise((resolve) => resolve(null)));

return renderResult;
};

beforeEach(() => {
testRenderer = createFleetTestRendererMock();
Expand All @@ -95,10 +100,8 @@ describe('useOnSubmit', () => {
});

describe('default API response', () => {
beforeEach(() => {
act(() => {
render();
});
beforeEach(async () => {
await render();
});

it('should set new values when package policy changes', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,17 +284,15 @@ describe('When on the package policy create page', () => {
let cancelButton: HTMLAnchorElement;

beforeEach(async () => {
await act(async () => {
render();
render();

cancelLink = renderResult.getByTestId(
'createPackagePolicy_cancelBackLink'
) as HTMLAnchorElement;
cancelLink = renderResult.getByTestId(
'createPackagePolicy_cancelBackLink'
) as HTMLAnchorElement;

cancelButton = (await renderResult.findByTestId(
'createPackagePolicyCancelButton'
)) as HTMLAnchorElement;
});
cancelButton = (await renderResult.findByTestId(
'createPackagePolicyCancelButton'
)) as HTMLAnchorElement;
});

test('should use custom "cancel" URL', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

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

import { createFleetTestRendererMock } from '../../../../../../mock';

Expand Down Expand Up @@ -36,7 +36,7 @@ describe('useHistoryBlock', () => {

act(() => renderer.mountHistory.push('/test'));
// needed because we have an async useEffect
await act(() => new Promise((resolve) => resolve()));
await waitFor(() => new Promise((resolve) => resolve(null)));

expect(renderer.startServices.overlays.openConfirm).toBeCalled();
expect(renderer.startServices.application.navigateToUrl).toBeCalledWith(
Expand All @@ -53,7 +53,7 @@ describe('useHistoryBlock', () => {

act(() => renderer.mountHistory.push('/test'));
// needed because we have an async useEffect
await act(() => new Promise((resolve) => resolve()));
await waitFor(() => new Promise((resolve) => resolve(null)));

expect(renderer.startServices.overlays.openConfirm).toBeCalled();
expect(renderer.startServices.application.navigateToUrl).not.toBeCalled();
Expand Down Expand Up @@ -81,7 +81,7 @@ describe('useHistoryBlock', () => {

act(() => renderer.mountHistory.push('/test?param=test'));
// needed because we have an async useEffect
await act(() => new Promise((resolve) => resolve()));
await waitFor(() => new Promise((resolve) => resolve(null)));

expect(renderer.startServices.overlays.openConfirm).toBeCalled();
expect(renderer.startServices.application.navigateToUrl).toBeCalledWith(
Expand All @@ -98,7 +98,7 @@ describe('useHistoryBlock', () => {

act(() => renderer.mountHistory.push('/test?param=test'));
// needed because we have an async useEffect
await act(() => new Promise((resolve) => resolve()));
await waitFor(() => new Promise((resolve) => resolve(null)));

expect(renderer.startServices.overlays.openConfirm).toBeCalled();
expect(renderer.startServices.application.navigateToUrl).not.toBeCalled();
Expand Down Expand Up @@ -127,7 +127,7 @@ describe('useHistoryBlock', () => {

act(() => renderer.mountHistory.push('/test#/hash'));
// needed because we have an async useEffect
await act(() => new Promise((resolve) => resolve()));
await waitFor(() => new Promise((resolve) => resolve(null)));

expect(renderer.startServices.overlays.openConfirm).toBeCalled();
expect(renderer.startServices.application.navigateToUrl).toBeCalledWith(
Expand All @@ -144,7 +144,7 @@ describe('useHistoryBlock', () => {

act(() => renderer.mountHistory.push('/test#/hash'));
// needed because we have an async useEffect
await act(() => new Promise((resolve) => resolve()));
await waitFor(() => new Promise((resolve) => resolve(null)));

expect(renderer.startServices.overlays.openConfirm).toBeCalled();
expect(renderer.startServices.application.navigateToUrl).not.toBeCalled();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
* 2.0.
*/

import { waitFor } from '@testing-library/react';
import { omit } from 'lodash';

import { sendGetPackageInfoByKey, sendUpgradePackagePolicyDryRun } from '../../../../../../hooks';
Expand Down Expand Up @@ -274,22 +275,22 @@ jest.mock('../../../../../../hooks/use_request', () => ({
describe('usePackagePolicy', () => {
it('should load the package policy if this is a not an upgrade', async () => {
const renderer = createFleetTestRendererMock();
const { result, waitForNextUpdate } = renderer.renderHook(() =>
const { result } = renderer.renderHook(() =>
usePackagePolicyWithRelatedData('package-policy-1', {})
);
await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));

expect(result.current.packagePolicy).toEqual(omit(mockPackagePolicy, 'id'));
});

it('should load the package policy if this is an upgrade', async () => {
const renderer = createFleetTestRendererMock();
const { result, waitForNextUpdate } = renderer.renderHook(() =>
const { result } = renderer.renderHook(() =>
usePackagePolicyWithRelatedData('package-policy-1', {
forceUpgrade: true,
})
);
await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(result.current.packagePolicy).toMatchInlineSnapshot(`
Object {
"description": "Nginx description",
Expand Down Expand Up @@ -514,12 +515,12 @@ describe('usePackagePolicy', () => {
isLoading: false,
} as any);
const renderer = createFleetTestRendererMock();
const { result, waitForNextUpdate } = renderer.renderHook(() =>
const { result } = renderer.renderHook(() =>
usePackagePolicyWithRelatedData('package-policy-2', {
forceUpgrade: true,
})
);
await waitForNextUpdate();
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(result.current.packagePolicy).toMatchInlineSnapshot(`
Object {
"description": "Nginx description",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
* 2.0.
*/

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

import { createFleetTestRendererMock } from '../../../../../../mock';

Expand Down
Loading

0 comments on commit ac4caed

Please sign in to comment.