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

# Backport

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

<!--- 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-12-09T13:15:29Z","message":"[React18]
Migrate test suites to account for testing library upgrades
obs-ux-management-team (#201164)\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.\r\n\r\n---------\r\n\r\nCo-authored-by: kibanamachine
<[email protected]>\r\nCo-authored-by:
Elastic Machine
<[email protected]>","sha":"7f1d43668106e662dc06bda67d33266a0e35da62","branchLabelMapping":{"^v9.0.0$":"main","^v8.18.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","backport:prev-minor","ci:project-deploy-observability","Team:obs-ux-management","React@18"],"title":"[React18]
Migrate test suites to account for testing library upgrades
obs-ux-management-team","number":201164,"url":"https://github.com/elastic/kibana/pull/201164","mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
obs-ux-management-team (#201164)\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.\r\n\r\n---------\r\n\r\nCo-authored-by: kibanamachine
<[email protected]>\r\nCo-authored-by:
Elastic Machine
<[email protected]>","sha":"7f1d43668106e662dc06bda67d33266a0e35da62"}},"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/201164","number":201164,"mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
obs-ux-management-team (#201164)\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.\r\n\r\n---------\r\n\r\nCo-authored-by: kibanamachine
<[email protected]>\r\nCo-authored-by:
Elastic Machine
<[email protected]>","sha":"7f1d43668106e662dc06bda67d33266a0e35da62"}}]}]
BACKPORT-->

Co-authored-by: Eyo O. Eyo <[email protected]>
  • Loading branch information
kibanamachine and eokoneyo authored Dec 11, 2024
1 parent 0f28d24 commit 3720840
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 3720840

Please sign in to comment.