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 ml-ui (#201161) (#201370)

# Backport

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

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

Co-authored-by: Eyo O. Eyo <[email protected]>
Co-authored-by: Elastic Machine <[email protected]>
  • Loading branch information
3 people authored Nov 26, 2024
1 parent 279795f commit 6241281
Show file tree
Hide file tree
Showing 14 changed files with 50 additions and 65 deletions.
3 changes: 1 addition & 2 deletions x-pack/packages/ml/data_grid/hooks/use_column_chart.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
*/

import React from 'react';
import { render } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import { render, renderHook } from '@testing-library/react';

import { KBN_FIELD_TYPES } from '@kbn/field-types';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useDatePickerContext } from './use_date_picker_context';
import { useTimefilter } from './use_timefilter';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import type { Category } from '@kbn/aiops-log-pattern-analysis/types';
import { useCreateFormattedExample } from './format_category';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';

jest.mock('../../hooks/use_eui_theme', () => ({
useIsDarkTheme: () => false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@

import type { ReactElement } from 'react';
import userEvent from '@testing-library/user-event';
import { render } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import { render, renderHook } from '@testing-library/react';

import type { SignificantItem } from '@kbn/ml-agg-utils';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { FilterQueryContextProvider, useFilterQueryUpdates } from './use_filters_query';
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { dataPluginMock as mockDataPlugin } from '@kbn/data-plugin/public/mocks';
import type { TimefilterConfig } from '@kbn/data-plugin/public/query';
import { Timefilter } from '@kbn/data-plugin/public/query';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@
*/

import React from 'react';
import { render } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import { render, renderHook } from '@testing-library/react';

import { KBN_FIELD_TYPES } from '@kbn/data-plugin/public';

Expand Down
34 changes: 11 additions & 23 deletions x-pack/plugins/ml/common/types/storage.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@

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

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

import type { Storage } from '@kbn/kibana-utils-plugin/public';
import { StorageContextProvider, useStorage } from '@kbn/ml-local-storage';
Expand Down Expand Up @@ -61,54 +62,43 @@ describe('useStorage', () => {
});

test('updates the storage value', async () => {
const { result, waitForNextUpdate } = renderHook(
() => useStorage('ml.gettingStarted.isDismissed'),
{
wrapper: Provider,
}
);
const { result } = renderHook(() => useStorage('ml.gettingStarted.isDismissed'), {
wrapper: Provider,
});

const [value, setValue] = result.current;

expect(value).toBe(true);

await act(async () => {
setValue(false);
await waitForNextUpdate();
});

expect(result.current[0]).toBe(false);
expect(mockSet).toHaveBeenCalledWith('ml.gettingStarted.isDismissed', false);
});

test('removes the storage value', async () => {
const { result, waitForNextUpdate } = renderHook(
() => useStorage('ml.gettingStarted.isDismissed'),
{
wrapper: Provider,
}
);
const { result } = renderHook(() => useStorage('ml.gettingStarted.isDismissed'), {
wrapper: Provider,
});

const [value, setValue] = result.current;

expect(value).toBe(true);

await act(async () => {
setValue(undefined);
await waitForNextUpdate();
});

expect(result.current[0]).toBe(undefined);
expect(mockRemove).toHaveBeenCalledWith('ml.gettingStarted.isDismissed');
});

test('updates the value on storage event', async () => {
const { result, waitForNextUpdate } = renderHook(
() => useStorage('ml.gettingStarted.isDismissed'),
{
wrapper: Provider,
}
);
const { result } = renderHook(() => useStorage('ml.gettingStarted.isDismissed'), {
wrapper: Provider,
});

expect(result.current[0]).toBe(true);

Expand All @@ -130,7 +120,6 @@ describe('useStorage', () => {
newValue: null,
})
);
await waitForNextUpdate();
});

expect(result.current[0]).toBe(undefined);
Expand All @@ -142,7 +131,6 @@ describe('useStorage', () => {
newValue: 'false',
})
);
await waitForNextUpdate();
});

expect(result.current[0]).toBe(false);
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 { of, throwError } from 'rxjs';
import { useMlNotifications, MlNotificationsContextProvider } from './ml_notifications_context';
import { useStorage } from '@kbn/ml-local-storage';
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 { act, renderHook } from '@testing-library/react';
import { useAsObservable } from './use_as_observable';

describe('useAsObservable', () => {
Expand All @@ -16,6 +16,8 @@ describe('useAsObservable', () => {
test('provides and observable preserving a reference', () => {
const { result, rerender } = renderHook(useAsObservable, { initialProps: 1 });

const initial = result.current;

let observableValue;
const subscriptionMock = jest.fn((v) => (observableValue = v));

Expand All @@ -27,15 +29,15 @@ describe('useAsObservable', () => {

act(() => rerender(1));

expect(result.all[0]).toStrictEqual(result.all[1]);
expect(initial).toStrictEqual(result.current);

expect(subscriptionMock).toHaveBeenCalledWith(1);
expect(subscriptionMock).toHaveBeenCalledTimes(1);
expect(observableValue).toEqual(1);
});

test('updates the subject with a new value', async () => {
const { result, rerender, waitForNextUpdate } = renderHook(useAsObservable, {
const { result, rerender } = renderHook(useAsObservable, {
initialProps: 'test',
});

Expand All @@ -50,7 +52,6 @@ describe('useAsObservable', () => {

await act(async () => {
rerender('test update');
await waitForNextUpdate();
});

expect(subscriptionMock).toHaveBeenCalledTimes(2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useMlKibana, useMlLicenseInfo } from '../contexts/kibana';
import { usePermissionCheck } from '../capabilities/check_capabilities';
import { useRouteResolver } from './use_resolver';
Expand Down Expand Up @@ -63,8 +63,8 @@ describe('useResolver', () => {
it.skip('redirects to the access denied page if some required capabilities are missing', async () => {
(usePermissionCheck as jest.Mock<boolean[]>).mockReturnValueOnce([false]);

const { waitForNextUpdate } = renderHook(() => useRouteResolver('full', ['canGetCalendars']));
await waitForNextUpdate();
renderHook(() => useRouteResolver('full', ['canGetCalendars']));
await waitFor(() => new Promise((resolve) => resolve(null)));
expect(useMlKibana().services.application.navigateToUrl).toHaveBeenCalled();
});
});
29 changes: 14 additions & 15 deletions x-pack/plugins/transform/public/app/hooks/use_index_data.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@

import React, { type FC, type PropsWithChildren } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, screen, waitFor } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import { render, screen, waitFor, renderHook } from '@testing-library/react';

import { __IntlProvider as IntlProvider } from '@kbn/i18n-react';
import type { CoreSetup } from '@kbn/core/public';
Expand Down Expand Up @@ -47,7 +46,7 @@ describe('Transform: useIndexData()', () => {
</QueryClientProvider>
);

const { result, waitForNextUpdate } = renderHook(
const { result } = renderHook(
() =>
useIndexData({
dataView: {
Expand All @@ -62,13 +61,13 @@ describe('Transform: useIndexData()', () => {
{ wrapper }
);

const IndexObj: UseIndexDataReturnType = result.current;

await waitForNextUpdate();
await waitFor(() => {
const IndexObj: UseIndexDataReturnType = result.current;

expect(IndexObj.errorMessage).toBe('');
expect(IndexObj.status).toBe(INDEX_STATUS.UNUSED);
expect(IndexObj.tableItems).toEqual([]);
expect(IndexObj.errorMessage).toBe('');
expect(IndexObj.status).toBe(INDEX_STATUS.UNUSED);
expect(IndexObj.tableItems).toEqual([]);
});
});

test('dataView set triggers loading', async () => {
Expand All @@ -78,7 +77,7 @@ describe('Transform: useIndexData()', () => {
</QueryClientProvider>
);

const { result, waitForNextUpdate } = renderHook(
const { result } = renderHook(
() =>
useIndexData({
dataView: {
Expand Down Expand Up @@ -108,11 +107,11 @@ describe('Transform: useIndexData()', () => {

const IndexObj: UseIndexDataReturnType = result.current;

await waitForNextUpdate();

expect(IndexObj.errorMessage).toBe('');
expect(IndexObj.status).toBe(INDEX_STATUS.LOADING);
expect(IndexObj.tableItems).toEqual([]);
await waitFor(() => {
expect(IndexObj.errorMessage).toBe('');
expect(IndexObj.status).toBe(INDEX_STATUS.LOADING);
expect(IndexObj.tableItems).toEqual([]);
});
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
*/

import React, { type FC, type PropsWithChildren } from 'react';
import { act, renderHook } from '@testing-library/react-hooks';

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

import { getTransformConfigMock } from './__mocks__/transform_config';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import React, { type FC, type PropsWithChildren } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';

jest.mock('../../../../app_dependencies');

Expand All @@ -19,12 +19,11 @@ describe('Transform: Transform List Actions', () => {
const wrapper: FC<PropsWithChildren<unknown>> = ({ children }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const { result, waitForNextUpdate } = renderHook(
() => useActions({ forceDisable: false, transformNodes: 1 }),
{ wrapper }
);
const { result } = renderHook(() => useActions({ forceDisable: false, transformNodes: 1 }), {
wrapper,
});

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

const actions = result.current.actions;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import React, { type FC, type PropsWithChildren } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';

import { useColumns } from './use_columns';

Expand All @@ -19,11 +19,11 @@ describe('Transform: Job List Columns', () => {
const wrapper: FC<PropsWithChildren<unknown>> = ({ children }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const { result, waitForNextUpdate } = renderHook(() => useColumns([], () => {}, 1, [], false), {
const { result } = renderHook(() => useColumns([], () => {}, 1, [], false), {
wrapper,
});

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

const columns: ReturnType<typeof useColumns>['columns'] = result.current.columns;

Expand Down

0 comments on commit 6241281

Please sign in to comment.