diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/correlations/use_failed_transactions_correlations.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/correlations/use_failed_transactions_correlations.test.tsx index 5432c70e57ab1..4b93123b589bf 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/correlations/use_failed_transactions_correlations.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/correlations/use_failed_transactions_correlations.test.tsx @@ -5,10 +5,11 @@ * 2.0. */ -import React, { ReactNode } from 'react'; +import React, { PropsWithChildren } from 'react'; import { merge } from 'lodash'; import { createMemoryHistory } from 'history'; -import { renderHook, act } from '@testing-library/react-hooks'; + +import { act, waitFor, renderHook } from '@testing-library/react'; import { ApmPluginContextValue } from '../../../context/apm_plugin/apm_plugin_context'; import { @@ -22,7 +23,7 @@ import { fromQuery } from '../../shared/links/url_helpers'; import { useFailedTransactionsCorrelations } from './use_failed_transactions_correlations'; import type { APIEndpoint } from '../../../../server'; -function wrapper({ children, error = false }: { children?: ReactNode; error: boolean }) { +function wrapper({ children, error = false }: PropsWithChildren<{ error?: boolean }>) { const getHttpMethodMock = (method: 'GET' | 'POST') => jest.fn().mockImplementation(async (pathname) => { await delay(100); @@ -107,17 +108,18 @@ describe('useFailedTransactionsCorrelations', () => { wrapper, }); - try { + await waitFor(() => expect(result.current.progress).toEqual({ isRunning: true, loaded: 0, - }); - expect(result.current.response).toEqual({ ccsWarning: false }); - expect(typeof result.current.startFetch).toEqual('function'); - expect(typeof result.current.cancelFetch).toEqual('function'); - } finally { - unmount(); - } + }) + ); + + expect(result.current.response).toEqual({ ccsWarning: false }); + expect(result.current.startFetch).toEqual(expect.any(Function)); + expect(result.current.cancelFetch).toEqual(expect.any(Function)); + + unmount(); }); it('should not have received any results after 50ms', async () => { @@ -125,21 +127,21 @@ describe('useFailedTransactionsCorrelations', () => { wrapper, }); - try { - jest.advanceTimersByTime(50); + jest.advanceTimersByTime(50); + await waitFor(() => expect(result.current.progress).toEqual({ isRunning: true, loaded: 0, - }); - expect(result.current.response).toEqual({ ccsWarning: false }); - } finally { - unmount(); - } + }) + ); + + expect(result.current.response).toEqual({ ccsWarning: false }); + unmount(); }); it('should receive partial updates and finish running', async () => { - const { result, unmount, waitFor } = renderHook(() => useFailedTransactionsCorrelations(), { + const { result, unmount } = renderHook(() => useFailedTransactionsCorrelations(), { wrapper, }); @@ -253,29 +255,37 @@ describe('useFailedTransactionsCorrelations', () => { }); describe('when throwing an error', () => { it('should automatically start fetching results', async () => { - const { result, unmount } = renderHook(() => useFailedTransactionsCorrelations(), { - wrapper, - initialProps: { - error: true, - }, + const { result, unmount } = renderHook(useFailedTransactionsCorrelations, { + wrapper: ({ children }) => + React.createElement( + wrapper, + { + error: true, + }, + children + ), }); - try { + await waitFor(() => expect(result.current.progress).toEqual({ isRunning: true, loaded: 0, - }); - } finally { - unmount(); - } + }) + ); + + unmount(); }); it('should still be running after 50ms', async () => { - const { result, unmount } = renderHook(() => useFailedTransactionsCorrelations(), { - wrapper, - initialProps: { - error: true, - }, + const { result, unmount } = renderHook(useFailedTransactionsCorrelations, { + wrapper: ({ children }) => + React.createElement( + wrapper, + { + error: true, + }, + children + ), }); try { @@ -292,11 +302,15 @@ describe('useFailedTransactionsCorrelations', () => { }); it('should stop and return an error after more than 100ms', async () => { - const { result, unmount, waitFor } = renderHook(() => useFailedTransactionsCorrelations(), { - wrapper, - initialProps: { - error: true, - }, + const { result, unmount } = renderHook(useFailedTransactionsCorrelations, { + wrapper: ({ children }) => + React.createElement( + wrapper, + { + error: true, + }, + children + ), }); try { @@ -316,7 +330,7 @@ describe('useFailedTransactionsCorrelations', () => { describe('when canceled', () => { it('should stop running', async () => { - const { result, unmount, waitFor } = renderHook(() => useFailedTransactionsCorrelations(), { + const { result, unmount } = renderHook(() => useFailedTransactionsCorrelations(), { wrapper, }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/correlations/use_latency_correlations.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/correlations/use_latency_correlations.test.tsx index 70446d1d2b1fd..e76420e3c1a92 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/correlations/use_latency_correlations.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/correlations/use_latency_correlations.test.tsx @@ -5,10 +5,11 @@ * 2.0. */ -import React, { ReactNode } from 'react'; +import React, { PropsWithChildren } from 'react'; import { merge } from 'lodash'; import { createMemoryHistory } from 'history'; -import { renderHook, act } from '@testing-library/react-hooks'; + +import { act, waitFor, renderHook } from '@testing-library/react'; import { ApmPluginContextValue } from '../../../context/apm_plugin/apm_plugin_context'; import { @@ -22,7 +23,7 @@ import { fromQuery } from '../../shared/links/url_helpers'; import { useLatencyCorrelations } from './use_latency_correlations'; import type { APIEndpoint } from '../../../../server'; -function wrapper({ children, error = false }: { children?: ReactNode; error: boolean }) { +function wrapper({ children, error = false }: PropsWithChildren<{ error?: boolean }>) { const getHttpMethodMock = (method: 'GET' | 'POST') => jest.fn().mockImplementation(async (pathname) => { await delay(100); @@ -86,16 +87,17 @@ function wrapper({ children, error = false }: { children?: ReactNode; error: boo } describe('useLatencyCorrelations', () => { - beforeEach(async () => { - jest.useFakeTimers({ legacyFakeTimers: true }); - }); - afterEach(() => { - jest.useRealTimers(); - }); - describe('when successfully loading results', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + it('should automatically start fetching results', async () => { - const { result, unmount } = renderHook(() => useLatencyCorrelations(), { + const { result, unmount } = renderHook(useLatencyCorrelations, { wrapper, }); @@ -113,7 +115,7 @@ describe('useLatencyCorrelations', () => { }); it('should not have received any results after 50ms', async () => { - const { result, unmount } = renderHook(() => useLatencyCorrelations(), { + const { result, unmount } = renderHook(useLatencyCorrelations, { wrapper, }); @@ -131,7 +133,7 @@ describe('useLatencyCorrelations', () => { }); it('should receive partial updates and finish running', async () => { - const { result, unmount, waitFor } = renderHook(() => useLatencyCorrelations(), { + const { result, unmount } = renderHook(useLatencyCorrelations, { wrapper, }); @@ -213,12 +215,17 @@ describe('useLatencyCorrelations', () => { }); describe('when throwing an error', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + it('should automatically start fetching results', async () => { - const { result, unmount } = renderHook(() => useLatencyCorrelations(), { - wrapper, - initialProps: { - error: true, - }, + const { result, unmount } = renderHook(useLatencyCorrelations, { + wrapper: ({ children }) => wrapper({ children, error: true }), }); try { @@ -232,11 +239,8 @@ describe('useLatencyCorrelations', () => { }); it('should still be running after 50ms', async () => { - const { result, unmount } = renderHook(() => useLatencyCorrelations(), { - wrapper, - initialProps: { - error: true, - }, + const { result, unmount } = renderHook(useLatencyCorrelations, { + wrapper: ({ children }) => wrapper({ children, error: true }), }); try { @@ -253,22 +257,21 @@ describe('useLatencyCorrelations', () => { }); it('should stop and return an error after more than 100ms', async () => { - const { result, unmount, waitFor } = renderHook(() => useLatencyCorrelations(), { - wrapper, - initialProps: { - error: true, - }, + const { result, unmount } = renderHook(useLatencyCorrelations, { + wrapper: ({ children }) => wrapper({ children, error: true }), }); try { - jest.advanceTimersByTime(150); - await waitFor(() => expect(result.current.progress.error).toBeDefined()); - - expect(result.current.progress).toEqual({ - error: 'Something went wrong', - isRunning: false, - loaded: 0, + act(() => { + jest.advanceTimersByTime(150); }); + await waitFor(() => + expect(result.current.progress).toEqual({ + error: 'Something went wrong', + isRunning: false, + loaded: 0, + }) + ); } finally { unmount(); } @@ -276,8 +279,16 @@ describe('useLatencyCorrelations', () => { }); describe('when canceled', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + it('should stop running', async () => { - const { result, unmount, waitFor } = renderHook(() => useLatencyCorrelations(), { + const { result, unmount } = renderHook(useLatencyCorrelations, { wrapper, }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/infra_overview/infra_tabs/use_tabs.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/infra_overview/infra_tabs/use_tabs.test.tsx index 245d4e90631a1..b1a1fea3924ee 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/infra_overview/infra_tabs/use_tabs.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/infra_overview/infra_tabs/use_tabs.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ import React, { ReactNode } from 'react'; -import { renderHook } from '@testing-library/react-hooks'; +import { renderHook } from '@testing-library/react'; import { useTabs } from './use_tabs'; import { createKibanaReactContext } from '@kbn/kibana-react-plugin/public'; import { CoreStart } from '@kbn/core/public'; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/empty_banner.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/empty_banner.test.tsx index 20149d0f40795..168180e89c97e 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/empty_banner.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/empty_banner.test.tsx @@ -58,11 +58,12 @@ describe('EmptyBanner', () => { it('does not render null', async () => { const component = renderWithTheme(, { wrapper }); - await act(async () => { + act(() => { cy.add({ data: { id: 'test id' } }); - await waitFor(() => { - expect(component.container.children.length).toBeGreaterThan(0); - }); + }); + + await waitFor(() => { + expect(component.container.children.length).toBeGreaterThan(0); }); }); }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx index 0f7fd67ae7c0f..31604d8934019 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/service_map/use_cytoscape_event_handlers.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook } from '@testing-library/react-hooks'; +import { renderHook } from '@testing-library/react'; import cytoscape from 'cytoscape'; import dagre from 'cytoscape-dagre'; import { EuiTheme } from '@kbn/kibana-react-plugin/common'; diff --git a/x-pack/plugins/observability_solution/apm/public/components/app/trace_link/trace_link.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/app/trace_link/trace_link.test.tsx index 3250702b0cb80..06f7101520bab 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/app/trace_link/trace_link.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/app/trace_link/trace_link.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { act, render, waitFor } from '@testing-library/react'; +import { render, waitFor } from '@testing-library/react'; import { shallow } from 'enzyme'; import React, { ReactNode } from 'react'; import { MemoryRouter } from 'react-router-dom'; @@ -67,12 +67,9 @@ describe('TraceLink', () => { }, }); - let result; - act(() => { - const component = render(, renderOptions); + const component = render(, renderOptions); - result = component.getByText('Fetching trace...'); - }); + const result = component.getByText('Fetching trace...'); await waitFor(() => {}); expect(result).toBeDefined(); }); diff --git a/x-pack/plugins/observability_solution/apm/public/components/routing/templates/apm_service_template/use_tabs.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/routing/templates/apm_service_template/use_tabs.test.tsx index 05c8464929d55..fee28395960c9 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/routing/templates/apm_service_template/use_tabs.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/routing/templates/apm_service_template/use_tabs.test.tsx @@ -6,7 +6,7 @@ */ import { CoreStart } from '@kbn/core/public'; import { createKibanaReactContext } from '@kbn/kibana-react-plugin/public'; -import { renderHook } from '@testing-library/react-hooks'; +import { renderHook } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import React, { ReactNode } from 'react'; import { ServerlessType } from '../../../../../common/serverless'; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/error_marker.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/error_marker.test.tsx index d71562e425e99..748b783661743 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/error_marker.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/charts/timeline/marker/error_marker.test.tsx @@ -5,8 +5,7 @@ * 2.0. */ -import { fireEvent } from '@testing-library/react'; -import { act } from '@testing-library/react-hooks'; +import { fireEvent, act } from '@testing-library/react'; import React, { ReactNode } from 'react'; import { MemoryRouter } from 'react-router-dom'; import { MockApmPluginContextWrapper } from '../../../../../context/apm_plugin/mock_apm_plugin_context'; diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/service_transactions_overview_link.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/service_transactions_overview_link.test.tsx index 54999ead161ba..ce2a56a3ecc81 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/service_transactions_overview_link.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/service_transactions_overview_link.test.tsx @@ -5,8 +5,7 @@ * 2.0. */ -import { render } from '@testing-library/react'; -import { renderHook } from '@testing-library/react-hooks'; +import { render, renderHook } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import React from 'react'; import { MockApmPluginContextWrapper } from '../../../../context/apm_plugin/mock_apm_plugin_context'; @@ -19,7 +18,7 @@ import { const history = createMemoryHistory(); function wrapper({ queryParams }: { queryParams?: Record }) { - return ({ children }: { children: React.ReactElement }) => ( + return ({ children }: React.PropsWithChildren) => ( {children} diff --git a/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/transaction_overview_link.test.tsx b/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/transaction_overview_link.test.tsx index bf095a4925fc9..a1836a2a336e0 100644 --- a/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/transaction_overview_link.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/components/shared/links/apm/transaction_overview_link.test.tsx @@ -5,8 +5,7 @@ * 2.0. */ -import { render } from '@testing-library/react'; -import { renderHook } from '@testing-library/react-hooks'; +import { render, renderHook } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import React from 'react'; import { MockApmPluginContextWrapper } from '../../../../context/apm_plugin/mock_apm_plugin_context'; @@ -15,7 +14,7 @@ import { TransactionOverviewLink, useTransactionsOverviewHref } from './transact const history = createMemoryHistory(); -function Wrapper({ children }: { children: React.ReactElement }) { +function Wrapper({ children }: React.PropsWithChildren) { return ( {children} diff --git a/x-pack/plugins/observability_solution/apm/public/hooks/use_breakpoints.test.tsx b/x-pack/plugins/observability_solution/apm/public/hooks/use_breakpoints.test.tsx index d311f48fa0e58..7a9a7aa33b6b2 100644 --- a/x-pack/plugins/observability_solution/apm/public/hooks/use_breakpoints.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/hooks/use_breakpoints.test.tsx @@ -6,7 +6,7 @@ */ import React, { FC, PropsWithChildren } from 'react'; -import { renderHook } from '@testing-library/react-hooks'; +import { renderHook } from '@testing-library/react'; import { EuiProvider } from '@elastic/eui'; import { useBreakpoints } from './use_breakpoints'; diff --git a/x-pack/plugins/observability_solution/apm/public/hooks/use_debounce.test.tsx b/x-pack/plugins/observability_solution/apm/public/hooks/use_debounce.test.tsx index 6701024eea9e9..98543601cab2a 100644 --- a/x-pack/plugins/observability_solution/apm/public/hooks/use_debounce.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/hooks/use_debounce.test.tsx @@ -4,11 +4,11 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { renderHook, act } from '@testing-library/react-hooks'; + +import { renderHook, act } from '@testing-library/react'; import { useStateDebounced } from './use_debounce'; // Replace 'your-module' with the actual module path describe('useStateDebounced', () => { - jest.useFakeTimers(); beforeAll(() => { // Mocks console.error so it won't polute tests output when testing the api throwing error jest.spyOn(console, 'error').mockImplementation(() => null); @@ -18,6 +18,14 @@ describe('useStateDebounced', () => { jest.restoreAllMocks(); }); + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + it('returns the initial value and a debounced setter function', () => { const { result } = renderHook(() => useStateDebounced('initialValue', 300)); @@ -34,7 +42,9 @@ describe('useStateDebounced', () => { result.current[1]('updatedValue'); }); expect(result.current[0]).toBe('initialValue'); - jest.advanceTimersByTime(300); + act(() => { + jest.advanceTimersByTime(300); + }); expect(result.current[0]).toBe('updatedValue'); }); @@ -44,12 +54,15 @@ describe('useStateDebounced', () => { act(() => { result.current[1]('updatedValue'); }); - jest.advanceTimersByTime(150); + act(() => { + jest.advanceTimersByTime(150); + }); expect(result.current[0]).toBe('initialValue'); act(() => { result.current[1]('newUpdatedValue'); + jest.advanceTimersByTime(400); }); - jest.advanceTimersByTime(400); + expect(result.current[0]).toBe('newUpdatedValue'); }); }); diff --git a/x-pack/plugins/observability_solution/apm/public/hooks/use_fetcher.test.tsx b/x-pack/plugins/observability_solution/apm/public/hooks/use_fetcher.test.tsx index 14c58ab3977ee..be61a03e2bd80 100644 --- a/x-pack/plugins/observability_solution/apm/public/hooks/use_fetcher.test.tsx +++ b/x-pack/plugins/observability_solution/apm/public/hooks/use_fetcher.test.tsx @@ -5,46 +5,42 @@ * 2.0. */ -import { renderHook, RenderHookResult } from '@testing-library/react-hooks'; -import React, { ReactNode } from 'react'; +import React from 'react'; +import { waitFor, act, renderHook, type RenderHookResult } from '@testing-library/react'; import { CoreStart } from '@kbn/core/public'; import { createKibanaReactContext } from '@kbn/kibana-react-plugin/public'; import { delay } from '../utils/test_helpers'; -import { FetcherResult, useFetcher, isPending, FETCH_STATUS } from './use_fetcher'; +import { useFetcher, isPending, FETCH_STATUS } from './use_fetcher'; // Wrap the hook with a provider so it can useKibana const KibanaReactContext = createKibanaReactContext({ notifications: { toasts: { add: () => {}, danger: () => {} } }, } as unknown as Partial); -interface WrapperProps { - children?: ReactNode; - callback: () => Promise; - args: string[]; -} -function wrapper({ children }: WrapperProps) { +function wrapper({ children }: React.PropsWithChildren) { return {children}; } describe('useFetcher', () => { describe('when resolving after 500ms', () => { - let hook: RenderHookResult< - WrapperProps, - FetcherResult & { - refetch: () => void; - } - >; + let hook: RenderHookResult, Parameters>; beforeEach(() => { - jest.useFakeTimers({ legacyFakeTimers: true }); + jest.useFakeTimers(); + async function fn() { await delay(500); return 'response from hook'; } - hook = renderHook(() => useFetcher(() => fn(), []), { wrapper }); + + hook = renderHook(() => useFetcher(fn, []), { wrapper }); }); - it('should have loading spinner initally', async () => { + afterEach(() => { + jest.useRealTimers(); + }); + + it('should have loading spinner initially', () => { expect(hook.result.current).toEqual({ data: undefined, error: undefined, @@ -53,8 +49,10 @@ describe('useFetcher', () => { }); }); - it('should still show loading spinner after 100ms', async () => { - jest.advanceTimersByTime(100); + it('should still show loading spinner after 100ms', () => { + act(() => { + jest.advanceTimersByTime(100); + }); expect(hook.result.current).toEqual({ data: undefined, @@ -65,8 +63,11 @@ describe('useFetcher', () => { }); it('should show success after 1 second', async () => { - jest.advanceTimersByTime(1000); - await hook.waitForNextUpdate(); + act(() => { + jest.advanceTimersByTime(1000); + }); + + await waitFor(() => expect(hook.result.current.status).toBe('success')); expect(hook.result.current).toEqual({ data: 'response from hook', @@ -78,23 +79,23 @@ describe('useFetcher', () => { }); describe('when throwing after 500ms', () => { - let hook: RenderHookResult< - WrapperProps, - FetcherResult & { - refetch: () => void; - } - >; + let hook: RenderHookResult, Parameters>; beforeEach(() => { - jest.useFakeTimers({ legacyFakeTimers: true }); + jest.useFakeTimers(); + async function fn(): Promise { await delay(500); throw new Error('Something went wrong'); } - hook = renderHook(() => useFetcher(() => fn(), []), { wrapper }); + hook = renderHook(() => useFetcher(fn, []), { wrapper }); + }); + + afterEach(() => { + jest.useRealTimers(); }); - it('should have loading spinner initally', async () => { + it('should have loading spinner initially', () => { expect(hook.result.current).toEqual({ data: undefined, error: undefined, @@ -103,8 +104,10 @@ describe('useFetcher', () => { }); }); - it('should still show loading spinner after 100ms', async () => { - jest.advanceTimersByTime(100); + it('should still show loading spinner after 100ms', () => { + act(() => { + jest.advanceTimersByTime(100); + }); expect(hook.result.current).toEqual({ data: undefined, @@ -115,8 +118,11 @@ describe('useFetcher', () => { }); it('should show error after 1 second', async () => { - jest.advanceTimersByTime(1000); - await hook.waitForNextUpdate(); + act(() => { + jest.advanceTimersByTime(1000); + }); + + await waitFor(() => expect(hook.result.current.status).toBe('failure')); expect(hook.result.current).toEqual({ data: undefined, @@ -128,20 +134,27 @@ describe('useFetcher', () => { }); describe('when a hook already has data', () => { - it('should show "first response" while loading "second response"', async () => { - jest.useFakeTimers({ legacyFakeTimers: true }); + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useRealTimers(); + }); + it('should show "first response" while loading "second response"', async () => { const hook = renderHook( /* eslint-disable-next-line react-hooks/exhaustive-deps */ ({ callback, args }) => useFetcher(callback, args), { initialProps: { - callback: async () => 'first response', + callback: () => Promise.resolve('first response'), args: ['a'], }, wrapper, } ); + expect(hook.result.current).toEqual({ data: undefined, error: undefined, @@ -149,15 +162,15 @@ describe('useFetcher', () => { status: 'loading', }); - await hook.waitForNextUpdate(); - // assert: first response has loaded and should be rendered - expect(hook.result.current).toEqual({ - data: 'first response', - error: undefined, - refetch: expect.any(Function), - status: 'success', - }); + await waitFor(() => + expect(hook.result.current).toEqual({ + data: 'first response', + error: undefined, + refetch: expect.any(Function), + status: 'success', + }) + ); // act: re-render hook with async callback hook.rerender({ @@ -168,55 +181,92 @@ describe('useFetcher', () => { args: ['b'], }); - jest.advanceTimersByTime(100); - - // assert: while loading new data the previous data should still be rendered - expect(hook.result.current).toEqual({ - data: 'first response', - error: undefined, - refetch: expect.any(Function), - status: 'loading', + act(() => { + jest.advanceTimersByTime(100); }); - jest.advanceTimersByTime(500); - await hook.waitForNextUpdate(); + // assert: while loading new data the previous data should still be rendered + await waitFor(() => + expect(hook.result.current).toEqual({ + data: 'first response', + error: undefined, + refetch: expect.any(Function), + status: 'loading', + }) + ); - // assert: "second response" has loaded and should be rendered - expect(hook.result.current).toEqual({ - data: 'second response', - error: undefined, - refetch: expect.any(Function), - status: 'success', + act(() => { + jest.advanceTimersByTime(500); }); + + await waitFor(() => + expect(hook.result.current).toEqual({ + data: 'second response', + error: undefined, + refetch: expect.any(Function), + status: 'success', + }) + ); }); it('should return the same object reference when data is unchanged between rerenders', async () => { + const initialProps = { + callback: () => Promise.resolve('data response'), + args: ['a'], + }; + const hook = renderHook( /* eslint-disable-next-line react-hooks/exhaustive-deps */ ({ callback, args }) => useFetcher(callback, args), { - initialProps: { - callback: async () => 'data response', - args: ['a'], - }, + initialProps, wrapper, } ); - await hook.waitForNextUpdate(); + + act(() => { + jest.runAllTimers(); + }); + + // assert: initial data has loaded; + await waitFor(() => + expect(hook.result.current).toEqual( + expect.objectContaining({ + data: 'data response', + status: 'success', + }) + ) + ); + const firstResult = hook.result.current; - hook.rerender(); + hook.rerender(initialProps); + + expect(hook.result.current).toEqual( + expect.objectContaining({ + data: 'data response', + status: 'success', + }) + ); + const secondResult = hook.result.current; // assert: subsequent rerender returns the same object reference expect(secondResult === firstResult).toEqual(true); hook.rerender({ - callback: async () => { - return 'second response'; - }, + callback: () => Promise.resolve('second response'), args: ['b'], }); - await hook.waitForNextUpdate(); + + await waitFor(() => + expect(hook.result.current).toEqual( + expect.objectContaining({ + data: 'second response', + status: 'success', + }) + ) + ); + const thirdResult = hook.result.current; // assert: rerender with different data returns a new object diff --git a/x-pack/plugins/observability_solution/apm/public/hooks/use_time_range.test.ts b/x-pack/plugins/observability_solution/apm/public/hooks/use_time_range.test.ts index 2bbc5c60ca91e..2f6c08aad8ccf 100644 --- a/x-pack/plugins/observability_solution/apm/public/hooks/use_time_range.test.ts +++ b/x-pack/plugins/observability_solution/apm/public/hooks/use_time_range.test.ts @@ -4,11 +4,12 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ -import { renderHook, RenderHookResult } from '@testing-library/react-hooks'; + +import { renderHook, RenderHookResult } from '@testing-library/react'; import { useTimeRange } from './use_time_range'; describe('useTimeRange', () => { - let hook: RenderHookResult[0], ReturnType>; + let hook: RenderHookResult, Parameters[0]>; beforeEach(() => { Date.now = jest.fn(() => new Date(Date.UTC(2021, 0, 1, 12)).valueOf()); diff --git a/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_container_metrics_charts.test.ts b/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_container_metrics_charts.test.ts index 392582d4f9eed..496029a8b436b 100644 --- a/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_container_metrics_charts.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_container_metrics_charts.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook } from '@testing-library/react-hooks'; +import { waitFor, renderHook } from '@testing-library/react'; import { ContainerMetricTypes } from '../charts/types'; import { useK8sContainerPageViewMetricsCharts, @@ -48,10 +48,10 @@ describe('useDockerContainerCharts', () => { async (metric) => { const expectedOrder = getContainerChartsExpectedOrder(metric); - const { result, waitForNextUpdate } = renderHook(() => + const { result } = renderHook(() => useDockerContainerPageViewMetricsCharts({ metricsDataViewId, metric }) ); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); const { charts } = result.current; @@ -68,13 +68,14 @@ describe('useDockerContainerCharts', () => { describe('useDockerKPIMetricsCharts', () => { it('should return an array of charts with correct order', async () => { const expectedOrder = ['cpuUsage', 'memoryUsage']; - const { result, waitForNextUpdate } = renderHook(() => + const { result } = renderHook(() => useDockerContainerKpiCharts({ dataViewId: metricsDataViewId }) ); - await waitForNextUpdate(); - expect(result.current).toHaveLength(expectedOrder.length); - result.current.forEach((chart, index) => { - expect(chart).toHaveProperty('id', expectedOrder[index]); + await waitFor(() => { + expect(result.current).toHaveLength(expectedOrder.length); + result.current.forEach((chart, index) => { + expect(chart).toHaveProperty('id', expectedOrder[index]); + }); }); }); }); @@ -86,10 +87,10 @@ describe('useK8sContainerCharts', () => { async (metric) => { const expectedOrder = getK8sContainerChartsExpectedOrder(metric); - const { result, waitForNextUpdate } = renderHook(() => + const { result } = renderHook(() => useK8sContainerPageViewMetricsCharts({ metricsDataViewId, metric }) ); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); const { charts } = result.current; @@ -106,13 +107,14 @@ describe('useK8sContainerCharts', () => { describe('useK8sContainerKPIMetricsCharts', () => { it('should return an array of charts with correct order', async () => { const expectedOrder = ['k8sCpuUsage', 'k8sMemoryUsage']; - const { result, waitForNextUpdate } = renderHook(() => + const { result } = renderHook(() => useK8sContainerKpiCharts({ dataViewId: metricsDataViewId }) ); - await waitForNextUpdate(); - expect(result.current).toHaveLength(expectedOrder.length); - result.current.forEach((chart, index) => { - expect(chart).toHaveProperty('id', expectedOrder[index]); + await waitFor(() => { + expect(result.current).toHaveLength(expectedOrder.length); + result.current.forEach((chart, index) => { + expect(chart).toHaveProperty('id', expectedOrder[index]); + }); }); }); }); diff --git a/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_host_metrics_charts.test.ts b/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_host_metrics_charts.test.ts index 006fae9bec753..f95ab156222eb 100644 --- a/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_host_metrics_charts.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_host_metrics_charts.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook } from '@testing-library/react-hooks'; +import { waitFor, renderHook } from '@testing-library/react'; import { HostMetricTypes } from '../charts/types'; import { useHostKpiCharts, useHostCharts, useKubernetesCharts } from './use_host_metrics_charts'; @@ -40,10 +40,8 @@ describe('useHostCharts', () => { async (metric) => { const expectedOrder = getHostChartsExpectedOrder(metric, false); - const { result, waitForNextUpdate } = renderHook(() => - useHostCharts({ dataViewId, metric }) - ); - await waitForNextUpdate(); + const { result } = renderHook(() => useHostCharts({ dataViewId, metric })); + await waitFor(() => new Promise((resolve) => resolve(null))); const { charts } = result.current; @@ -60,10 +58,10 @@ describe('useHostCharts', () => { async (metric) => { const expectedOrder = getHostChartsExpectedOrder(metric, true); - const { result, waitForNextUpdate } = renderHook(() => + const { result } = renderHook(() => useHostCharts({ dataViewId, metric, overview: true }) ); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); const { charts } = result.current; @@ -80,10 +78,8 @@ describe('useHostCharts', () => { describe('useKubernetesCharts', () => { it('should return an array of charts with correct order - overview', async () => { - const { result, waitForNextUpdate } = renderHook(() => - useKubernetesCharts({ dataViewId, overview: true }) - ); - await waitForNextUpdate(); + const { result } = renderHook(() => useKubernetesCharts({ dataViewId, overview: true })); + await waitFor(() => new Promise((resolve) => resolve(null))); const expectedOrder = ['nodeCpuCapacity', 'nodeMemoryCapacity']; @@ -97,8 +93,8 @@ describe('useKubernetesCharts', () => { }); it('should return an array of charts with correct order', async () => { - const { result, waitForNextUpdate } = renderHook(() => useKubernetesCharts({ dataViewId })); - await waitForNextUpdate(); + const { result } = renderHook(() => useKubernetesCharts({ dataViewId })); + await waitFor(() => new Promise((resolve) => resolve(null))); const expectedOrder = [ 'nodeCpuCapacity', @@ -119,8 +115,8 @@ describe('useKubernetesCharts', () => { describe('useHostKpiCharts', () => { it('should return an array of charts with correct order', async () => { - const { result, waitForNextUpdate } = renderHook(() => useHostKpiCharts({ dataViewId })); - await waitForNextUpdate(); + const { result } = renderHook(() => useHostKpiCharts({ dataViewId })); + await waitFor(() => new Promise((resolve) => resolve(null))); const expectedOrder = ['cpuUsage', 'normalizedLoad1m', 'memoryUsage', 'diskUsage']; @@ -140,10 +136,8 @@ describe('useHostKpiCharts', () => { getSubtitle: () => 'Custom Subtitle', }; - const { result, waitForNextUpdate } = renderHook(() => - useHostKpiCharts({ dataViewId, ...options }) - ); - await waitForNextUpdate(); + const { result } = renderHook(() => useHostKpiCharts({ dataViewId, ...options })); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(result.current).toHaveLength(4); diff --git a/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_loading_state.test.ts b/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_loading_state.test.ts index becd0e81c0a9a..2475c97cec0e8 100644 --- a/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_loading_state.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_loading_state.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { act, renderHook } from '@testing-library/react-hooks'; +import { act, waitFor, renderHook } from '@testing-library/react'; import { useLoadingState } from './use_loading_state'; import { useDatePickerContext, type UseDateRangeProviderProps } from './use_date_picker'; import { BehaviorSubject, EMPTY, of, Subject, Subscription, skip } from 'rxjs'; @@ -102,7 +102,7 @@ describe('useLoadingState', () => { }); it('should set isAutoRefreshRequestPending to true when there are requests pending', async () => { - const { result, unmount, waitFor } = renderHook(() => useLoadingState()); + const { result, unmount } = renderHook(() => useLoadingState()); let receivedValue = false; subscription.add( @@ -128,7 +128,7 @@ describe('useLoadingState', () => { }); it('should set isAutoRefreshRequestPending to false when all requests complete', async () => { - const { result, unmount, waitFor } = renderHook(() => useLoadingState()); + const { result, unmount } = renderHook(() => useLoadingState()); let receivedValue = true; subscription.add( @@ -153,7 +153,7 @@ describe('useLoadingState', () => { }); it('should not call updateSearchSessionId if waitUntilNextSessionCompletesMock$ returns empty', async () => { - const { unmount, waitFor } = renderHook(() => useLoadingState()); + const { unmount } = renderHook(() => useLoadingState()); // waitUntilNextSessionCompletes$ returns EMPTY when the status is loading or none sessionState$.next(SearchSessionState.Loading); @@ -171,7 +171,7 @@ describe('useLoadingState', () => { }); it('should call updateSearchSessionId when waitUntilNextSessionCompletesMock$ returns', async () => { - const { unmount, waitFor } = renderHook(() => useLoadingState()); + const { unmount } = renderHook(() => useLoadingState()); // waitUntilNextSessionCompletes$ returns something when the status is Completed or BackgroundCompleted sessionState$.next(SearchSessionState.Loading); diff --git a/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_profiling_kuery.test.tsx b/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_profiling_kuery.test.tsx index 10325ce51f81f..0d4db96a23fad 100644 --- a/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_profiling_kuery.test.tsx +++ b/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_profiling_kuery.test.tsx @@ -7,7 +7,7 @@ import React from 'react'; import { MemoryRouter, useHistory } from 'react-router-dom'; -import { renderHook, act } from '@testing-library/react-hooks'; +import { renderHook, act } from '@testing-library/react'; import { useProfilingKuery } from './use_profiling_kuery'; import { useAssetDetailsRenderPropsContext } from './use_asset_details_render_props'; diff --git a/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_request_observable.test.ts b/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_request_observable.test.ts index 9ca4bd17ca34b..9be24cbfcf3f4 100644 --- a/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_request_observable.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/components/asset_details/hooks/use_request_observable.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook, act } from '@testing-library/react-hooks'; +import { act, waitFor, renderHook } from '@testing-library/react'; import { useRequestObservable } from './use_request_observable'; import { type RequestState, useLoadingStateContext } from './use_loading_state'; import { useDatePickerContext, type UseDateRangeProviderProps } from './use_date_picker'; @@ -69,7 +69,7 @@ describe('useRequestObservable', () => { }); it('should process a valid request function', async () => { - const { result, waitFor, unmount } = renderHook(() => useRequestObservable()); + const { result, unmount } = renderHook(() => useRequestObservable()); act(() => { result.current.request$.next(() => Promise.resolve()); @@ -85,7 +85,7 @@ describe('useRequestObservable', () => { }); it('should be able to make new requests if isAutoRefreshRequestPending is false', async () => { - const { result, waitFor, unmount } = renderHook(() => useRequestObservable()); + const { result, unmount } = renderHook(() => useRequestObservable()); act(() => { isAutoRefreshRequestPendingMock$.next(false); @@ -102,7 +102,7 @@ describe('useRequestObservable', () => { }); it('should block new requests when isAutoRefreshRequestPending is true', async () => { - const { result, waitFor, unmount } = renderHook(() => useRequestObservable()); + const { result, unmount } = renderHook(() => useRequestObservable()); act(() => { isAutoRefreshRequestPendingMock$.next(false); @@ -123,7 +123,7 @@ describe('useRequestObservable', () => { }); it('should not block new requests when auto-refresh is paused', async () => { - const { result, waitFor, unmount } = renderHook(() => useRequestObservable()); + const { result, unmount } = renderHook(() => useRequestObservable()); act(() => { autoRefreshConfig$.next({ isPaused: true, interval: 5000 }); @@ -144,7 +144,7 @@ describe('useRequestObservable', () => { }); it('should complete the request when an error is thrown', async () => { - const { result, waitFor, unmount } = renderHook(() => useRequestObservable()); + const { result, unmount } = renderHook(() => useRequestObservable()); act(() => { autoRefreshConfig$.next({ isPaused: true, interval: 5000 }); diff --git a/x-pack/plugins/observability_solution/infra/public/containers/ml/infra_ml_module_status.test.ts b/x-pack/plugins/observability_solution/infra/public/containers/ml/infra_ml_module_status.test.ts index 80d538ef1e50b..b754537107e46 100644 --- a/x-pack/plugins/observability_solution/infra/public/containers/ml/infra_ml_module_status.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/containers/ml/infra_ml_module_status.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook, act } from '@testing-library/react-hooks'; +import { renderHook, act } from '@testing-library/react'; import { useModuleStatus } from './infra_ml_module_status'; describe('useModuleStatus', () => { diff --git a/x-pack/plugins/observability_solution/infra/public/containers/plugin_config_context.test.tsx b/x-pack/plugins/observability_solution/infra/public/containers/plugin_config_context.test.tsx index 62c582a818240..a33c3432f06fa 100644 --- a/x-pack/plugins/observability_solution/infra/public/containers/plugin_config_context.test.tsx +++ b/x-pack/plugins/observability_solution/infra/public/containers/plugin_config_context.test.tsx @@ -6,15 +6,15 @@ */ import type { InfraConfig } from '../../common/plugin_config_types'; -import { renderHook } from '@testing-library/react-hooks'; +import { renderHook } from '@testing-library/react'; import React from 'react'; import { PluginConfigProvider, usePluginConfig } from './plugin_config_context'; describe('usePluginConfig()', () => { it('throws an error if the context value was not set before using the hook', () => { - const { result } = renderHook(() => usePluginConfig()); - - expect(result.error).not.toEqual(undefined); + expect(() => renderHook(() => usePluginConfig())).toThrow( + /PluginConfigContext value was not initialized./ + ); }); it('returns the plugin config what was set through the provider', () => { @@ -40,7 +40,6 @@ describe('usePluginConfig()', () => { }, }); - expect(result.error).toEqual(undefined); expect(result.current).toEqual(config); }); }); diff --git a/x-pack/plugins/observability_solution/infra/public/hooks/use_alerts_count.test.ts b/x-pack/plugins/observability_solution/infra/public/hooks/use_alerts_count.test.ts index 2b2dc755c94c1..87db1db65398a 100644 --- a/x-pack/plugins/observability_solution/infra/public/hooks/use_alerts_count.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/hooks/use_alerts_count.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook } from '@testing-library/react-hooks'; +import { waitFor, renderHook } from '@testing-library/react'; import { ALERT_STATUS, ValidFeatureId } from '@kbn/rule-data-utils'; import { useAlertsCount } from './use_alerts_count'; @@ -66,12 +66,12 @@ describe('useAlertsCount', () => { it('should return the mocked data from API', async () => { mockedPostAPI.mockResolvedValue(mockedAlertsCountResponse); - const { result, waitForNextUpdate } = renderHook(() => useAlertsCount({ featureIds })); + const { result } = renderHook(() => useAlertsCount({ featureIds })); expect(result.current.loading).toBe(true); expect(result.current.alertsCount).toEqual(undefined); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); const { alertsCount, loading, error } = result.current; expect(alertsCount).toEqual(expectedResult); @@ -88,15 +88,13 @@ describe('useAlertsCount', () => { }; mockedPostAPI.mockResolvedValue(mockedAlertsCountResponse); - const { waitForNextUpdate } = renderHook(() => + renderHook(() => useAlertsCount({ featureIds, query, }) ); - await waitForNextUpdate(); - const body = JSON.stringify({ aggs: { count: { @@ -108,9 +106,11 @@ describe('useAlertsCount', () => { size: 0, }); - expect(mockedPostAPI).toHaveBeenCalledWith( - '/internal/rac/alerts/find', - expect.objectContaining({ body }) + await waitFor(() => + expect(mockedPostAPI).toHaveBeenCalledWith( + '/internal/rac/alerts/find', + expect.objectContaining({ body }) + ) ); }); @@ -118,10 +118,8 @@ describe('useAlertsCount', () => { const error = new Error('Fetch Alerts Count Failed'); mockedPostAPI.mockRejectedValueOnce(error); - const { result, waitForNextUpdate } = renderHook(() => useAlertsCount({ featureIds })); - - await waitForNextUpdate(); + const { result } = renderHook(() => useAlertsCount({ featureIds })); - 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/infra/public/hooks/use_lens_attributes.test.ts b/x-pack/plugins/observability_solution/infra/public/hooks/use_lens_attributes.test.ts index 0a619069c04a4..5e5f00fd66139 100644 --- a/x-pack/plugins/observability_solution/infra/public/hooks/use_lens_attributes.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/hooks/use_lens_attributes.test.ts @@ -6,7 +6,7 @@ */ import 'jest-canvas-mock'; -import { renderHook } from '@testing-library/react-hooks'; +import { waitFor, renderHook } from '@testing-library/react'; import { useLensAttributes } from './use_lens_attributes'; import { coreMock } from '@kbn/core/public/mocks'; import { type KibanaReactContextValue, useKibana } from '@kbn/kibana-react-plugin/public'; @@ -72,15 +72,15 @@ describe('useLensAttributes hook', () => { }); it('should return the basic lens attributes', async () => { - const { waitForNextUpdate } = renderHook(() => useLensAttributes(params)); - await waitForNextUpdate(); - - expect(LensConfigBuilderMock.mock.instances[0].build).toHaveBeenCalledWith(params); + renderHook(() => useLensAttributes(params)); + await waitFor(() => + expect(LensConfigBuilderMock.mock.instances[0].build).toHaveBeenCalledWith(params) + ); }); it('should return extra actions', async () => { - const { result, waitForNextUpdate } = renderHook(() => useLensAttributes(params)); - await waitForNextUpdate(); + const { result } = renderHook(() => useLensAttributes(params)); + await waitFor(() => new Promise((resolve) => resolve(null))); const extraActions = result.current.getExtraActions({ timeRange: { diff --git a/x-pack/plugins/observability_solution/infra/public/pages/link_to/use_host_ip_to_name.test.ts b/x-pack/plugins/observability_solution/infra/public/pages/link_to/use_host_ip_to_name.test.ts index 150416a204b05..2a9d56a6f4dfa 100644 --- a/x-pack/plugins/observability_solution/infra/public/pages/link_to/use_host_ip_to_name.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/pages/link_to/use_host_ip_to_name.test.ts @@ -6,7 +6,7 @@ */ import { useHostIpToName } from './use_host_ip_to_name'; -import { renderHook } from '@testing-library/react-hooks'; +import { waitFor, renderHook } from '@testing-library/react'; const renderUseHostIpToNameHook = () => renderHook((props) => useHostIpToName(props.ipAddress, props.indexPattern), { @@ -32,10 +32,10 @@ jest.mock('@kbn/kibana-react-plugin/public', () => { describe('useHostIpToName Hook', () => { it('should basically work', async () => { mockedFetch.mockResolvedValue({ host: 'example-01' } as any); - const { result, waitForNextUpdate } = renderUseHostIpToNameHook(); + const { result } = renderUseHostIpToNameHook(); expect(result.current.name).toBe(null); expect(result.current.loading).toBe(true); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(result.current.name).toBe('example-01'); expect(result.current.loading).toBe(false); expect(result.current.error).toBe(null); @@ -44,10 +44,10 @@ describe('useHostIpToName Hook', () => { it('should handle errors', async () => { const error = new Error('Host not found'); mockedFetch.mockRejectedValue(error); - const { result, waitForNextUpdate } = renderUseHostIpToNameHook(); + const { result } = renderUseHostIpToNameHook(); expect(result.current.name).toBe(null); expect(result.current.loading).toBe(true); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(result.current.name).toBe(null); expect(result.current.loading).toBe(false); expect(result.current.error).toBe(error); @@ -56,16 +56,16 @@ describe('useHostIpToName Hook', () => { it('should reset errors', async () => { const error = new Error('Host not found'); mockedFetch.mockRejectedValue(error); - const { result, waitForNextUpdate, rerender } = renderUseHostIpToNameHook(); + const { result, rerender } = renderUseHostIpToNameHook(); expect(result.current.name).toBe(null); expect(result.current.loading).toBe(true); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(result.current.name).toBe(null); expect(result.current.loading).toBe(false); expect(result.current.error).toBe(error); mockedFetch.mockResolvedValue({ host: 'example-01' } as any); rerender({ ipAddress: '192.168.1.2', indexPattern: 'metricbeat-*' }); - await waitForNextUpdate(); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(result.current.name).toBe('example-01'); expect(result.current.loading).toBe(false); expect(result.current.error).toBe(null); diff --git a/x-pack/plugins/observability_solution/infra/public/pages/metrics/hosts/hooks/use_hosts_table.test.ts b/x-pack/plugins/observability_solution/infra/public/pages/metrics/hosts/hooks/use_hosts_table.test.ts index a0ebb20184912..abae2d5cadbff 100644 --- a/x-pack/plugins/observability_solution/infra/public/pages/metrics/hosts/hooks/use_hosts_table.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/pages/metrics/hosts/hooks/use_hosts_table.test.ts @@ -6,7 +6,7 @@ */ import { type HostNodeRow, useHostsTable } from './use_hosts_table'; -import { renderHook } from '@testing-library/react-hooks'; +import { renderHook } from '@testing-library/react'; import { InfraAssetMetricsItem } from '../../../../../common/http_api'; import * as useUnifiedSearchHooks from './use_unified_search'; import * as useHostsViewHooks from './use_hosts_view'; diff --git a/x-pack/plugins/observability_solution/infra/public/pages/metrics/hosts/hooks/use_metrics_charts.test.ts b/x-pack/plugins/observability_solution/infra/public/pages/metrics/hosts/hooks/use_metrics_charts.test.ts index b76d5938f0cb5..9d68b3ff76e77 100644 --- a/x-pack/plugins/observability_solution/infra/public/pages/metrics/hosts/hooks/use_metrics_charts.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/pages/metrics/hosts/hooks/use_metrics_charts.test.ts @@ -6,16 +6,14 @@ */ import type { LensSeriesLayer } from '@kbn/lens-embeddable-utils/config_builder'; -import { renderHook } from '@testing-library/react-hooks'; +import { waitFor, renderHook } from '@testing-library/react'; import { PAGE_SIZE_OPTIONS } from '../constants'; import { useMetricsCharts } from './use_metrics_charts'; describe('useMetricsCharts', () => { it('should return an array of charts with breakdown config', async () => { - const { result, waitForNextUpdate } = renderHook(() => - useMetricsCharts({ dataViewId: 'dataViewId' }) - ); - await waitForNextUpdate(); + const { result } = renderHook(() => useMetricsCharts({ dataViewId: 'dataViewId' })); + await waitFor(() => new Promise((resolve) => resolve(null))); expect(result.current).toHaveLength(11); @@ -29,10 +27,8 @@ describe('useMetricsCharts', () => { }); it('should return an array of charts with correct order', async () => { - const { result, waitForNextUpdate } = renderHook(() => - useMetricsCharts({ dataViewId: 'dataViewId' }) - ); - await waitForNextUpdate(); + const { result } = renderHook(() => useMetricsCharts({ dataViewId: 'dataViewId' })); + await waitFor(() => new Promise((resolve) => resolve(null))); const expectedOrder = [ 'cpuUsage', diff --git a/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.test.ts b/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.test.ts index 7fe7b8b3fe18c..533857130b114 100644 --- a/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/hooks/use_waffle_filters.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook, act } from '@testing-library/react-hooks'; +import { renderHook, act } from '@testing-library/react'; import { DataView } from '@kbn/data-views-plugin/common'; import { useWaffleFilters, WaffleFiltersState } from './use_waffle_filters'; import { TIMESTAMP_FIELD } from '../../../../../common/constants'; diff --git a/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts b/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts index 50f4e95b58a37..757a0e955b4df 100644 --- a/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts +++ b/x-pack/plugins/observability_solution/infra/public/pages/metrics/inventory_view/hooks/use_waffle_options.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook, act } from '@testing-library/react-hooks'; +import { renderHook, act } from '@testing-library/react'; import { useWaffleOptions, WaffleOptionsState } from './use_waffle_options'; diff --git a/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx b/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx index bcea796c3b00a..0e70071f199ff 100644 --- a/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx +++ b/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metric_explorer_state.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook, act } from '@testing-library/react-hooks'; +import { renderHook, act } from '@testing-library/react'; import { useMetricsExplorerState } from './use_metric_explorer_state'; import { MetricsExplorerOptionsContainer } from './use_metrics_explorer_options'; import React from 'react'; @@ -75,6 +75,10 @@ describe('useMetricsExplorerState', () => { delete STORE.MetricsExplorerTimeRange; }); + afterEach(() => { + jest.clearAllMocks(); + }); + it('should just work', async () => { mockedUseMetricsExplorerData.mockReturnValue({ isLoading: false, @@ -92,12 +96,14 @@ describe('useMetricsExplorerState', () => { describe('handleRefresh', () => { it('should trigger an addition request when handleRefresh is called', async () => { const { result } = renderUseMetricsExplorerStateHook(); - expect(result.all.length).toBe(2); - const numberOfHookCalls = result.all.length; + + const numberOfHookCalls = mockedUseMetricsExplorerData.mock.calls.length; + + expect(numberOfHookCalls).toEqual(2); act(() => { result.current.refresh(); }); - expect(result.all.length).toBe(numberOfHookCalls + 1); + expect(mockedUseMetricsExplorerData).toHaveBeenCalledTimes(numberOfHookCalls + 1); }); }); diff --git a/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx b/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx index 202ae51990ad2..8cc6bff922d92 100644 --- a/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx +++ b/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_data.test.tsx @@ -9,7 +9,7 @@ import React, { FC, PropsWithChildren } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { useMetricsExplorerData } from './use_metrics_explorer_data'; import { DataView } from '@kbn/data-views-plugin/common'; -import { renderHook } from '@testing-library/react-hooks'; +import { waitFor, act, renderHook } from '@testing-library/react'; import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public'; import { @@ -108,15 +108,14 @@ describe('useMetricsExplorerData Hook', () => { it('should just work', async () => { mockedFetch.mockResolvedValue(resp); - const { result, waitForNextUpdate } = renderUseMetricsExplorerDataHook(); + const { result } = renderUseMetricsExplorerDataHook(); expect(result.current.data).toBeUndefined(); expect(result.current.isLoading).toBe(true); - await waitForNextUpdate(); + await waitFor(() => expect(result.current.isLoading).toBe(false)); expect(result.current.data!.pages[0]).toEqual(resp); - expect(result.current.isLoading).toBe(false); const { series } = result.current.data!.pages[0]; expect(series).toBeDefined(); expect(series.length).toBe(3); @@ -124,12 +123,11 @@ describe('useMetricsExplorerData Hook', () => { it('should paginate', async () => { mockedFetch.mockResolvedValue(resp); - const { result, waitForNextUpdate } = renderUseMetricsExplorerDataHook(); + const { result } = renderUseMetricsExplorerDataHook(); expect(result.current.data).toBeUndefined(); expect(result.current.isLoading).toBe(true); - await waitForNextUpdate(); + await waitFor(() => expect(result.current.isLoading).toBe(false)); expect(result.current.data!.pages[0]).toEqual(resp); - expect(result.current.isLoading).toBe(false); const { series } = result.current.data!.pages[0]; expect(series).toBeDefined(); expect(series.length).toBe(3); @@ -137,41 +135,45 @@ describe('useMetricsExplorerData Hook', () => { pageInfo: { total: 10, afterKey: 'host-06' }, series: [createSeries('host-04'), createSeries('host-05'), createSeries('host-06')], } as any); - result.current.fetchNextPage(); - await waitForNextUpdate(); - expect(result.current.isLoading).toBe(false); - const { series: nextSeries } = result.current.data!.pages[1]; - expect(nextSeries).toBeDefined(); - expect(nextSeries.length).toBe(3); + await act(async () => { + await result.current.fetchNextPage(); + }); + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + const { series: nextSeries } = result.current.data!.pages[1]; + expect(nextSeries).toBeDefined(); + expect(nextSeries.length).toBe(3); + }); }); it('should reset error upon recovery', async () => { const error = new Error('Network Error'); mockedFetch.mockRejectedValue(error); - const { result, waitForNextUpdate } = renderUseMetricsExplorerDataHook(); + const { result } = renderUseMetricsExplorerDataHook(); expect(result.current.data).toBeUndefined(); expect(result.current.error).toEqual(null); expect(result.current.isLoading).toBe(true); - await waitForNextUpdate(); + await waitFor(() => expect(result.current.isLoading).toBe(false)); expect(result.current.data).toBeUndefined(); expect(result.current.error).toEqual(error); - expect(result.current.isLoading).toBe(false); mockedFetch.mockResolvedValue(resp as any); - result.current.refetch(); - await waitForNextUpdate(); - expect(result.current.data!.pages[0]).toEqual(resp); - expect(result.current.isLoading).toBe(false); - expect(result.current.error).toBe(null); + await act(async () => { + await result.current.refetch(); + }); + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + expect(result.current.data!.pages[0]).toEqual(resp); + expect(result.current.error).toBe(null); + }); }); it('should not paginate on option change', async () => { mockedFetch.mockResolvedValue(resp as any); - const { result, waitForNextUpdate, rerender } = renderUseMetricsExplorerDataHook(); + const { result, rerender } = renderUseMetricsExplorerDataHook(); expect(result.current.data).toBeUndefined(); expect(result.current.isLoading).toBe(true); - await waitForNextUpdate(); + await waitFor(() => expect(result.current.isLoading).toBe(false)); expect(result.current.data!.pages[0]).toEqual(resp); - expect(result.current.isLoading).toBe(false); const { series } = result.current.data!.pages[0]; expect(series).toBeDefined(); expect(series.length).toBe(3); @@ -187,19 +189,19 @@ describe('useMetricsExplorerData Hook', () => { timestamps, }); expect(result.current.isLoading).toBe(true); - await waitForNextUpdate(); - expect(result.current.data!.pages[0]).toEqual(resp); - expect(result.current.isLoading).toBe(false); + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + expect(result.current.data!.pages[0]).toEqual(resp); + }); }); it('should not paginate on time change', async () => { mockedFetch.mockResolvedValue(resp as any); - const { result, waitForNextUpdate, rerender } = renderUseMetricsExplorerDataHook(); + const { result, rerender } = renderUseMetricsExplorerDataHook(); expect(result.current.data).toBeUndefined(); expect(result.current.isLoading).toBe(true); - await waitForNextUpdate(); + await waitFor(() => expect(result.current.isLoading).toBe(false)); expect(result.current.data!.pages[0]).toEqual(resp); - expect(result.current.isLoading).toBe(false); const { series } = result.current.data!.pages[0]; expect(series).toBeDefined(); expect(series.length).toBe(3); @@ -211,8 +213,9 @@ describe('useMetricsExplorerData Hook', () => { timestamps: { fromTimestamp: 1678378092225, toTimestamp: 1678381693477, interval: '>=10s' }, }); expect(result.current.isLoading).toBe(true); - await waitForNextUpdate(); - expect(result.current.data!.pages[0]).toEqual(resp); - expect(result.current.isLoading).toBe(false); + await waitFor(() => { + expect(result.current.isLoading).toBe(false); + expect(result.current.data!.pages[0]).toEqual(resp); + }); }); }); diff --git a/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_options.test.tsx b/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_options.test.tsx index 795728fa8d8ef..f5c257e1f86ac 100644 --- a/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_options.test.tsx +++ b/x-pack/plugins/observability_solution/infra/public/pages/metrics/metrics_explorer/hooks/use_metrics_explorer_options.test.tsx @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook, act } from '@testing-library/react-hooks'; +import { renderHook, act } from '@testing-library/react'; import { useMetricsExplorerOptions, MetricsExplorerOptions, diff --git a/x-pack/plugins/observability_solution/infra/public/utils/data_search/use_data_search_request.test.tsx b/x-pack/plugins/observability_solution/infra/public/utils/data_search/use_data_search_request.test.tsx index 33369c1125e15..08907b1627086 100644 --- a/x-pack/plugins/observability_solution/infra/public/utils/data_search/use_data_search_request.test.tsx +++ b/x-pack/plugins/observability_solution/infra/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/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx b/x-pack/plugins/observability_solution/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx index a4b01be03d80b..24433f23bc677 100644 --- a/x-pack/plugins/observability_solution/infra/public/utils/data_search/use_latest_partial_data_search_response.test.tsx +++ b/x-pack/plugins/observability_solution/infra/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'; diff --git a/x-pack/plugins/observability_solution/inventory/public/hooks/use_detail_view_redirect.test.ts b/x-pack/plugins/observability_solution/inventory/public/hooks/use_detail_view_redirect.test.ts index 233c1a1076b79..d0406aa32884d 100644 --- a/x-pack/plugins/observability_solution/inventory/public/hooks/use_detail_view_redirect.test.ts +++ b/x-pack/plugins/observability_solution/inventory/public/hooks/use_detail_view_redirect.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook } from '@testing-library/react-hooks'; +import { renderHook } from '@testing-library/react'; import { useDetailViewRedirect } from './use_detail_view_redirect'; import { useKibana } from './use_kibana'; import { diff --git a/x-pack/plugins/observability_solution/inventory/public/hooks/use_is_loading_complete.test.ts b/x-pack/plugins/observability_solution/inventory/public/hooks/use_is_loading_complete.test.ts index 61306a0b66a3b..4706301eb0fca 100644 --- a/x-pack/plugins/observability_solution/inventory/public/hooks/use_is_loading_complete.test.ts +++ b/x-pack/plugins/observability_solution/inventory/public/hooks/use_is_loading_complete.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook } from '@testing-library/react-hooks'; +import { renderHook } from '@testing-library/react'; import { useIsLoadingComplete } from './use_is_loading_complete'; describe('useIsLoadingComplete', () => { diff --git a/x-pack/plugins/observability_solution/ux/public/components/app/rum_dashboard/visitor_breakdown_map/use_layer_list.test.ts b/x-pack/plugins/observability_solution/ux/public/components/app/rum_dashboard/visitor_breakdown_map/use_layer_list.test.ts index f4e733baf6ef7..025481c6b879b 100644 --- a/x-pack/plugins/observability_solution/ux/public/components/app/rum_dashboard/visitor_breakdown_map/use_layer_list.test.ts +++ b/x-pack/plugins/observability_solution/ux/public/components/app/rum_dashboard/visitor_breakdown_map/use_layer_list.test.ts @@ -5,7 +5,7 @@ * 2.0. */ -import { renderHook } from '@testing-library/react-hooks'; +import { renderHook } from '@testing-library/react'; import { mockLayerList } from './__mocks__/regions_layer.mock'; import { useLayerList } from './use_layer_list';