From 1f0f8d2c529e7b4ed9803b51bcb58e3809c418dc Mon Sep 17 00:00:00 2001 From: "Eyo O. Eyo" <7893459+eokoneyo@users.noreply.github.com> Date: Mon, 25 Nov 2024 11:49:51 +0100 Subject: [PATCH] [React18] Migrate test suites to account for testing library upgrades obs-ux-logs-team (#201148) 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: Elastic Machine --- .../src/use_boolean/use_boolean.test.ts | 2 +- .../use_fields_metadata.test.ts | 18 ++++++-------- .../logs/log_summary/log_summary.test.tsx | 24 +++++++++---------- .../use_data_search_request.test.tsx | 2 +- ...test_partial_data_search_response.test.tsx | 2 +- 5 files changed, 22 insertions(+), 26 deletions(-) diff --git a/packages/kbn-react-hooks/src/use_boolean/use_boolean.test.ts b/packages/kbn-react-hooks/src/use_boolean/use_boolean.test.ts index 8d5583e926bac..9711d54823d35 100644 --- a/packages/kbn-react-hooks/src/use_boolean/use_boolean.test.ts +++ b/packages/kbn-react-hooks/src/use_boolean/use_boolean.test.ts @@ -7,7 +7,7 @@ * License v3.0 only", or the "Server Side Public License, v 1". */ -import { act, cleanup, renderHook } from '@testing-library/react-hooks'; +import { renderHook, act, cleanup } from '@testing-library/react'; import { useBoolean } from './use_boolean'; diff --git a/x-pack/plugins/fields_metadata/public/hooks/use_fields_metadata/use_fields_metadata.test.ts b/x-pack/plugins/fields_metadata/public/hooks/use_fields_metadata/use_fields_metadata.test.ts index eaae7c5542c0b..8f69c11a10432 100644 --- a/x-pack/plugins/fields_metadata/public/hooks/use_fields_metadata/use_fields_metadata.test.ts +++ b/x-pack/plugins/fields_metadata/public/hooks/use_fields_metadata/use_fields_metadata.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook } from '@testing-library/react-hooks'; +import { waitFor, renderHook } from '@testing-library/react'; import { createUseFieldsMetadataHook, UseFieldsMetadataParams } from './use_fields_metadata'; import { FindFieldsMetadataResponsePayload } from '../../../common/latest'; @@ -46,12 +46,12 @@ describe('useFieldsMetadata', () => { it('should return the fieldsMetadata value from the API', async () => { fieldsMetadataClient.find.mockResolvedValue(mockedFieldsMetadataResponse); - const { result, waitForNextUpdate } = renderHook(() => useFieldsMetadata()); + const { result } = renderHook(() => useFieldsMetadata()); expect(result.current.loading).toBe(true); expect(result.current.fieldsMetadata).toEqual(undefined); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); const { fieldsMetadata, loading, error } = result.current; expect(fieldsMetadata).toEqual(fields); @@ -68,21 +68,17 @@ describe('useFieldsMetadata', () => { dataset: 'dataset_name', }; - const { waitForNextUpdate } = renderHook(() => useFieldsMetadata(params)); + renderHook(() => useFieldsMetadata(params)); - await waitForNextUpdate(); - - expect(fieldsMetadataClient.find).toHaveBeenCalledWith(params); + await waitFor(() => expect(fieldsMetadataClient.find).toHaveBeenCalledWith(params)); }); it('should return an error if the API call fails', async () => { const error = new Error('Fetch fields metadata Failed'); fieldsMetadataClient.find.mockRejectedValueOnce(error); - const { result, waitForNextUpdate } = renderHook(() => useFieldsMetadata()); - - await waitForNextUpdate(); + const { result } = renderHook(() => useFieldsMetadata()); - expect(result.current.error?.message).toMatch(error.message); + await waitFor(() => expect(result.current.error?.message).toMatch(error.message)); }); }); diff --git a/x-pack/plugins/observability_solution/logs_shared/public/containers/logs/log_summary/log_summary.test.tsx b/x-pack/plugins/observability_solution/logs_shared/public/containers/logs/log_summary/log_summary.test.tsx index 183950edf9777..8635df14731a5 100644 --- a/x-pack/plugins/observability_solution/logs_shared/public/containers/logs/log_summary/log_summary.test.tsx +++ b/x-pack/plugins/observability_solution/logs_shared/public/containers/logs/log_summary/log_summary.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook } from '@testing-library/react-hooks'; +import { waitFor, renderHook } from '@testing-library/react'; // We are using this inside a `jest.mock` call. Jest requires dynamic dependencies to be prefixed with `mock` import { coreMock as mockCoreMock } from '@kbn/core/public/mocks'; @@ -56,14 +56,14 @@ describe('useLogSummary hook', () => { .mockResolvedValueOnce(firstMockResponse) .mockResolvedValueOnce(secondMockResponse); - const { result, waitForNextUpdate, rerender } = renderHook( + const { result, rerender } = renderHook( ({ logViewReference }) => useLogSummary(logViewReference, startTimestamp, endTimestamp, null), { initialProps: { logViewReference: LOG_VIEW_REFERENCE }, } ); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(fetchLogSummaryMock).toHaveBeenCalledTimes(1); expect(fetchLogSummaryMock).toHaveBeenLastCalledWith( @@ -75,7 +75,7 @@ describe('useLogSummary hook', () => { expect(result.current.buckets).toEqual(firstMockResponse.data.buckets); rerender({ logViewReference: CHANGED_LOG_VIEW_REFERENCE }); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(fetchLogSummaryMock).toHaveBeenCalledTimes(2); expect(fetchLogSummaryMock).toHaveBeenLastCalledWith( @@ -101,7 +101,7 @@ describe('useLogSummary hook', () => { .mockResolvedValueOnce(firstMockResponse) .mockResolvedValueOnce(secondMockResponse); - const { result, waitForNextUpdate, rerender } = renderHook( + const { result, rerender } = renderHook( ({ filterQuery }) => useLogSummary(LOG_VIEW_REFERENCE, startTimestamp, endTimestamp, filterQuery), { @@ -109,7 +109,7 @@ describe('useLogSummary hook', () => { } ); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(fetchLogSummaryMock).toHaveBeenCalledTimes(1); expect(fetchLogSummaryMock).toHaveBeenLastCalledWith( @@ -121,7 +121,7 @@ describe('useLogSummary hook', () => { expect(result.current.buckets).toEqual(firstMockResponse.data.buckets); rerender({ filterQuery: 'CHANGED_FILTER_QUERY' }); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(fetchLogSummaryMock).toHaveBeenCalledTimes(2); expect(fetchLogSummaryMock).toHaveBeenLastCalledWith( @@ -139,7 +139,7 @@ describe('useLogSummary hook', () => { .mockResolvedValueOnce(createMockResponse([])); const firstRange = createMockDateRange(); - const { waitForNextUpdate, rerender } = renderHook( + const { rerender } = renderHook( ({ startTimestamp, endTimestamp }) => useLogSummary(LOG_VIEW_REFERENCE, startTimestamp, endTimestamp, null), { @@ -147,7 +147,7 @@ describe('useLogSummary hook', () => { } ); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(fetchLogSummaryMock).toHaveBeenCalledTimes(1); expect(fetchLogSummaryMock).toHaveBeenLastCalledWith( expect.objectContaining({ @@ -160,7 +160,7 @@ describe('useLogSummary hook', () => { const secondRange = createMockDateRange('now-20s', 'now'); rerender(secondRange); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(fetchLogSummaryMock).toHaveBeenCalledTimes(2); expect(fetchLogSummaryMock).toHaveBeenLastCalledWith( @@ -176,7 +176,7 @@ describe('useLogSummary hook', () => { fetchLogSummaryMock.mockResolvedValueOnce(createMockResponse([])); const firstRange = createMockDateRange(); - const { waitForNextUpdate, rerender } = renderHook( + const { rerender } = renderHook( ({ startTimestamp, endTimestamp }) => useLogSummary(LOG_VIEW_REFERENCE, startTimestamp, endTimestamp, null), { @@ -188,7 +188,7 @@ describe('useLogSummary hook', () => { // intentionally don't wait for an update to test the throttling rerender(secondRange); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(fetchLogSummaryMock).toHaveBeenCalledTimes(1); expect(fetchLogSummaryMock).toHaveBeenLastCalledWith( diff --git a/x-pack/plugins/observability_solution/logs_shared/public/utils/data_search/use_data_search_request.test.tsx b/x-pack/plugins/observability_solution/logs_shared/public/utils/data_search/use_data_search_request.test.tsx index 33369c1125e15..08907b1627086 100644 --- a/x-pack/plugins/observability_solution/logs_shared/public/utils/data_search/use_data_search_request.test.tsx +++ b/x-pack/plugins/observability_solution/logs_shared/public/utils/data_search/use_data_search_request.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { act, renderHook } from '@testing-library/react-hooks'; +import { renderHook, act } from '@testing-library/react'; import React from 'react'; import { firstValueFrom, Observable, of, Subject } from 'rxjs'; import type { ISearchGeneric, IKibanaSearchResponse } from '@kbn/search-types'; diff --git a/x-pack/plugins/observability_solution/logs_shared/public/utils/data_search/use_latest_partial_data_search_response.test.tsx b/x-pack/plugins/observability_solution/logs_shared/public/utils/data_search/use_latest_partial_data_search_response.test.tsx index a4b01be03d80b..24433f23bc677 100644 --- a/x-pack/plugins/observability_solution/logs_shared/public/utils/data_search/use_latest_partial_data_search_response.test.tsx +++ b/x-pack/plugins/observability_solution/logs_shared/public/utils/data_search/use_latest_partial_data_search_response.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { act, renderHook } from '@testing-library/react-hooks'; +import { renderHook, act } from '@testing-library/react'; import { BehaviorSubject, Observable, of, Subject } from 'rxjs'; import { IKibanaSearchRequest } from '@kbn/search-types'; import { ParsedDataSearchRequestDescriptor, ParsedKibanaSearchResponse } from './types';