[React18] Migrate test suites to account for testing library upgrades obs-ux-infra_services-team (#201168)

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 <elasticmachine@users.noreply.github.com>
This commit is contained in:
Eyo O. Eyo 2024-11-25 15:18:14 +01:00 committed by GitHub
parent d28d2c3415
commit 691f493cd4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
36 changed files with 394 additions and 312 deletions

View file

@ -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,
});

View file

@ -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,
});

View file

@ -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';

View file

@ -58,11 +58,12 @@ describe('EmptyBanner', () => {
it('does not render null', async () => {
const component = renderWithTheme(<EmptyBanner />, { 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);
});
});
});

View file

@ -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';

View file

@ -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(<TraceLink />, renderOptions);
const component = render(<TraceLink />, renderOptions);
result = component.getByText('Fetching trace...');
});
const result = component.getByText('Fetching trace...');
await waitFor(() => {});
expect(result).toBeDefined();
});

View file

@ -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';

View file

@ -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';

View file

@ -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<string, unknown> }) {
return ({ children }: { children: React.ReactElement }) => (
return ({ children }: React.PropsWithChildren) => (
<MockApmPluginContextWrapper history={history}>
<MockUrlParamsContextProvider params={queryParams}>{children}</MockUrlParamsContextProvider>
</MockApmPluginContextWrapper>

View file

@ -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 (
<MockApmPluginContextWrapper history={history}>
<MockUrlParamsContextProvider>{children}</MockUrlParamsContextProvider>

View file

@ -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';

View file

@ -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');
});
});

View file

@ -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<CoreStart>);
interface WrapperProps {
children?: ReactNode;
callback: () => Promise<string>;
args: string[];
}
function wrapper({ children }: WrapperProps) {
function wrapper({ children }: React.PropsWithChildren) {
return <KibanaReactContext.Provider>{children}</KibanaReactContext.Provider>;
}
describe('useFetcher', () => {
describe('when resolving after 500ms', () => {
let hook: RenderHookResult<
WrapperProps,
FetcherResult<string> & {
refetch: () => void;
}
>;
let hook: RenderHookResult<ReturnType<typeof useFetcher>, Parameters<typeof useFetcher>>;
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<string> & {
refetch: () => void;
}
>;
let hook: RenderHookResult<ReturnType<typeof useFetcher>, Parameters<typeof useFetcher>>;
beforeEach(() => {
jest.useFakeTimers({ legacyFakeTimers: true });
jest.useFakeTimers();
async function fn(): Promise<string> {
await delay(500);
throw new Error('Something went wrong');
}
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,
@ -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);
act(() => {
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',
await waitFor(() =>
expect(hook.result.current).toEqual({
data: 'first response',
error: undefined,
refetch: expect.any(Function),
status: 'loading',
})
);
act(() => {
jest.advanceTimersByTime(500);
});
jest.advanceTimersByTime(500);
await hook.waitForNextUpdate();
// 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',
});
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

View file

@ -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<Parameters<typeof useTimeRange>[0], ReturnType<typeof useTimeRange>>;
let hook: RenderHookResult<ReturnType<typeof useTimeRange>, Parameters<typeof useTimeRange>[0]>;
beforeEach(() => {
Date.now = jest.fn(() => new Date(Date.UTC(2021, 0, 1, 12)).valueOf());

View file

@ -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]);
});
});
});
});

View file

@ -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);

View file

@ -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);

View file

@ -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';

View file

@ -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 });

View file

@ -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', () => {

View file

@ -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);
});
});

View file

@ -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 }));
const { result } = renderHook(() => useAlertsCount({ featureIds }));
await waitForNextUpdate();
expect(result.current.error?.message).toMatch(error.message);
await waitFor(() => expect(result.current.error?.message).toMatch(error.message));
});
});

View file

@ -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: {

View file

@ -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);

View file

@ -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';

View file

@ -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',

View file

@ -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';

View file

@ -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';

View file

@ -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);
});
});

View file

@ -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);
});
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import {
useMetricsExplorerOptions,
MetricsExplorerOptions,

View file

@ -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';

View file

@ -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';

View file

@ -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 {

View file

@ -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', () => {

View file

@ -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';