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

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.
  • Loading branch information
eokoneyo authored Nov 22, 2024
1 parent 62fad39 commit 9ad5576
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 9ad5576

Please sign in to comment.