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

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.

(cherry picked from commit 4fbcf07)
  • Loading branch information
eokoneyo committed Nov 22, 2024
1 parent 54a410c commit 7dc8220
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 7dc8220

Please sign in to comment.