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
… obs-ux-management-team (elastic#201164)

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: kibanamachine <[email protected]>
Co-authored-by: Elastic Machine <[email protected]>
(cherry picked from commit 7f1d436)
  • Loading branch information
eokoneyo committed Dec 9, 2024
1 parent 4928233 commit 1b2af3c
Show file tree
Hide file tree
Showing 37 changed files with 437 additions and 461 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,9 @@
*/
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { httpServiceMock } from '@kbn/core-http-browser-mocks';
import {
type UseAlertsHistory,
useAlertsHistory,
type Props as useAlertsHistoryProps,
} from './use_alerts_history';
import { useAlertsHistory } from './use_alerts_history';

const queryClient = new QueryClient({
logger: {
Expand Down Expand Up @@ -44,7 +40,7 @@ describe('useAlertsHistory', () => {

it('returns no data with error when http client is not provided', async () => {
const http = undefined;
const { result, waitFor } = renderHook<useAlertsHistoryProps, UseAlertsHistory>(
const { result } = renderHook(
() =>
useAlertsHistory({
http,
Expand All @@ -56,18 +52,14 @@ describe('useAlertsHistory', () => {
wrapper,
}
);
await act(async () => {
await waitFor(() => result.current.isError);
});
expect(result.current.isError).toBeTruthy();
await waitFor(() => expect(result.current.isError).toBeTruthy());
expect(result.current.isSuccess).toBeFalsy();
expect(result.current.isLoading).toBeFalsy();
});

it('returns no data when API error', async () => {
mockServices.http.post.mockRejectedValueOnce(new Error('ES error'));

const { result, waitFor } = renderHook<useAlertsHistoryProps, UseAlertsHistory>(
const { result } = renderHook(
() =>
useAlertsHistory({
...mockServices,
Expand All @@ -79,10 +71,7 @@ describe('useAlertsHistory', () => {
wrapper,
}
);
await act(async () => {
await waitFor(() => result.current.isError);
});
expect(result.current.isError).toBeTruthy();
await waitFor(() => expect(result.current.isError).toBeTruthy());
expect(result.current.isSuccess).toBeFalsy();
expect(result.current.isLoading).toBeFalsy();
});
Expand Down Expand Up @@ -130,7 +119,7 @@ describe('useAlertsHistory', () => {
},
});

const { result, waitFor } = renderHook<useAlertsHistoryProps, UseAlertsHistory>(
const { result } = renderHook(
() =>
useAlertsHistory({
...mockServices,
Expand All @@ -142,9 +131,7 @@ describe('useAlertsHistory', () => {
wrapper,
}
);
await act(async () => {
await waitFor(() => result.current.isSuccess);
});
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(result.current.isLoading).toBeFalsy();
expect(result.current.isError).toBeFalsy();
expect(result.current.data.avgTimeToRecoverUS).toEqual(134959464.2857143);
Expand All @@ -167,7 +154,7 @@ describe('useAlertsHistory', () => {
},
});

const { result, waitFor } = renderHook<useAlertsHistoryProps, UseAlertsHistory>(
const { result } = renderHook(
() =>
useAlertsHistory({
...mockServices,
Expand All @@ -181,11 +168,7 @@ describe('useAlertsHistory', () => {
wrapper,
}
);

await act(async () => {
await waitFor(() => result.current.isSuccess);
});

await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(mockServices.http.post).toBeCalledWith('/internal/rac/alerts/find', {
body:
'{"size":0,"rule_type_ids":["apm"],"consumers":["foo"],"query":{"bool":{"must":[' +
Expand Down Expand Up @@ -215,7 +198,7 @@ describe('useAlertsHistory', () => {
},
});

const { result, waitFor } = renderHook<useAlertsHistoryProps, UseAlertsHistory>(
const { result } = renderHook(
() =>
useAlertsHistory({
...mockServices,
Expand All @@ -229,10 +212,7 @@ describe('useAlertsHistory', () => {
}
);

await act(async () => {
await waitFor(() => result.current.isSuccess);
});

await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(mockServices.http.post).toBeCalledWith('/internal/rac/alerts/find', {
body:
'{"size":0,"rule_type_ids":["apm"],"query":{"bool":{"must":[' +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import React from 'react';

import { allSeriesKey, reportTypeKey, UrlStorageContextProvider } from './use_series_storage';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useLensAttributes } from './use_lens_attributes';
import { ReportTypes } from '../configurations/constants';
import { mockDataView } from '../rtl_helpers';
Expand Down Expand Up @@ -66,9 +66,15 @@ describe('useExpViewTimeRange', function () {
jest.spyOn(lensHook, 'useLensFormulaHelper').mockReturnValue(formulaHelper);
});

const lensAttributesSpy = jest.spyOn(lensAttributes, 'LensAttributes');
const lensAttributesSpy = jest
.spyOn(lensAttributes, 'LensAttributes')
.mockImplementation(function (...args) {
return {
getJSON: () => {},
} as lensAttributes.LensAttributes;
});

function Wrapper({ children }: { children: JSX.Element }) {
function Wrapper({ children }: React.PropsWithChildren) {
return (
<ExploratoryViewContextProvider
reportTypes={reportTypesList}
Expand All @@ -78,7 +84,9 @@ describe('useExpViewTimeRange', function () {
theme$={themeServiceMock.createTheme$()}
{...coreMock.createStart()}
>
<UrlStorageContextProvider storage={storage}>{children}</UrlStorageContextProvider>
<UrlStorageContextProvider storage={storage}>
{React.createElement(React.Fragment, {}, children)}
</UrlStorageContextProvider>
</ExploratoryViewContextProvider>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
*/

import React, { useEffect } from 'react';
import { act, renderHook } from '@testing-library/react-hooks';
import { Router, Route } from '@kbn/shared-ux-router';
import { render } from '@testing-library/react';
import { render, renderHook, act } from '@testing-library/react';
import { UrlStorageContextProvider, useSeriesStorage, reportTypeKey } from './use_series_storage';
import { getHistoryFromUrl } from '../rtl_helpers';
import type { AppDataType } from '../types';
Expand Down Expand Up @@ -135,7 +134,7 @@ describe('userSeriesStorage', function () {
});

it('ensures that only one series has a breakdown', () => {
function wrapper({ children }: { children: React.ReactElement }) {
function wrapper({ children }: React.PropsWithChildren) {
return (
<UrlStorageContextProvider
storage={{
Expand All @@ -145,7 +144,7 @@ describe('userSeriesStorage', function () {
set: jest.fn(),
}}
>
{children}
{React.createElement(React.Fragment, {}, children)}
</UrlStorageContextProvider>
);
}
Expand All @@ -166,7 +165,7 @@ describe('userSeriesStorage', function () {

it('sets reportType when calling applyChanges', () => {
const setStorage = jest.fn();
function wrapper({ children }: { children: React.ReactElement }) {
function wrapper({ children }: React.PropsWithChildren) {
return (
<UrlStorageContextProvider
storage={{
Expand All @@ -178,7 +177,7 @@ describe('userSeriesStorage', function () {
set: setStorage,
}}
>
{children}
{React.createElement(React.Fragment, {}, children)}
</UrlStorageContextProvider>
);
}
Expand All @@ -197,7 +196,7 @@ describe('userSeriesStorage', function () {

it('returns reportType in state, not url storage, from hook', () => {
const setStorage = jest.fn();
function wrapper({ children }: { children: React.ReactElement }) {
function wrapper({ children }: React.PropsWithChildren) {
return (
<UrlStorageContextProvider
storage={{
Expand All @@ -209,7 +208,7 @@ describe('userSeriesStorage', function () {
set: setStorage,
}}
>
{children}
{React.createElement(React.Fragment, {}, children)}
</UrlStorageContextProvider>
);
}
Expand All @@ -225,7 +224,7 @@ describe('userSeriesStorage', function () {
it('ensures that telemetry is called', () => {
const trackEvent = jest.fn();
jest.spyOn(useTrackMetric, 'useUiTracker').mockReturnValue(trackEvent);
function wrapper({ children }: { children: React.ReactElement }) {
function wrapper({ children }: React.PropsWithChildren) {
return (
<UrlStorageContextProvider
storage={{
Expand All @@ -237,7 +236,7 @@ describe('userSeriesStorage', function () {
set: jest.fn(),
}}
>
{children}
{React.createElement(React.Fragment, {}, children)}
</UrlStorageContextProvider>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import React from 'react';

import { allSeriesKey, reportTypeKey, UrlStorageContextProvider } from './use_series_storage';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useExpViewTimeRange } from './use_time_range';
import { ReportTypes } from '../configurations/constants';
import { createKbnUrlStateStorage } from '@kbn/kibana-utils-plugin/public';
Expand Down Expand Up @@ -43,9 +43,14 @@ const mockMultipleSeries = [
describe('useExpViewTimeRange', function () {
const storage = createKbnUrlStateStorage({ useHash: false });

function Wrapper({ children }: { children: JSX.Element }) {
return <UrlStorageContextProvider storage={storage}>{children}</UrlStorageContextProvider>;
function Wrapper({ children }: React.PropsWithChildren) {
return (
<UrlStorageContextProvider storage={storage}>
{React.createElement(React.Fragment, {}, children)}
</UrlStorageContextProvider>
);
}

it('should return expected result when there is one series', async function () {
await storage.set(allSeriesKey, mockSingleSeries);
await storage.set(reportTypeKey, ReportTypes.KPI);
Expand Down
Loading

0 comments on commit 1b2af3c

Please sign in to comment.