Skip to content

Commit

Permalink
[React18] Migrate test suites to account for testing library upgrades…
Browse files Browse the repository at this point in the history
… search-kibana (#201157)

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 <[email protected]>
  • Loading branch information
eokoneyo and elasticmachine authored Dec 16, 2024
1 parent c92899e commit 90b77c6
Show file tree
Hide file tree
Showing 14 changed files with 92 additions and 101 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,7 @@
* 2.0.
*/
import type { DeeplyMockedKeys } from '@kbn/utility-types-jest';
import {
act,
renderHook,
type RenderHookResult,
type WrapperComponent,
} from '@testing-library/react-hooks';
import { renderHook, act, type RenderHookResult } from '@testing-library/react';
import { merge } from 'lodash';
import React, { PropsWithChildren } from 'react';
import { BehaviorSubject, Observable, of, Subject } from 'rxjs';
Expand All @@ -33,7 +28,7 @@ import type { NotificationsStart } from '@kbn/core/public';
import { KibanaContextProvider } from '@kbn/kibana-react-plugin/public';
import { AssistantScope } from '@kbn/ai-assistant-common';

let hookResult: RenderHookResult<UseConversationProps, UseConversationResult>;
let hookResult: RenderHookResult<UseConversationResult, UseConversationProps>;

type MockedService = DeeplyMockedKeys<Omit<AIAssistantAppService, 'conversations'>> & {
conversations: DeeplyMockedKeys<
Expand Down Expand Up @@ -81,34 +76,32 @@ const useKibanaMockServices = {
};

describe('useConversation', () => {
let wrapper: WrapperComponent<PropsWithChildren<UseConversationProps>>;
const wrapper = ({ children }: PropsWithChildren) => (
<KibanaContextProvider services={useKibanaMockServices}>{children}</KibanaContextProvider>
);

beforeEach(() => {
afterEach(() => {
jest.clearAllMocks();
wrapper = ({ children }: PropsWithChildren<unknown>) => (
<KibanaContextProvider services={useKibanaMockServices}>{children}</KibanaContextProvider>
);
});

describe('with initial messages and a conversation id', () => {
beforeEach(() => {
hookResult = renderHook(useConversation, {
initialProps: {
chatService: mockChatService,
connectorId: 'my-connector',
initialMessages: [
{
'@timestamp': new Date().toISOString(),
message: { content: '', role: MessageRole.User },
},
],
initialConversationId: 'foo',
},
wrapper,
});
});
it('throws an error', () => {
expect(hookResult.result.error).toBeTruthy();
expect(() =>
renderHook(useConversation, {
initialProps: {
chatService: mockChatService,
connectorId: 'my-connector',
initialMessages: [
{
'@timestamp': new Date().toISOString(),
message: { content: '', role: MessageRole.User },
},
],
initialConversationId: 'foo',
},
wrapper,
})
).toThrow(/Cannot set initialMessages if initialConversationId is set/);
});
});

Expand Down Expand Up @@ -434,25 +427,29 @@ describe('useConversation', () => {

describe('when the title is updated', () => {
describe('without a stored conversation', () => {
beforeEach(() => {
hookResult = renderHook(useConversation, {
initialProps: {
chatService: mockChatService,
connectorId: 'my-connector',
initialMessages: [
{
'@timestamp': new Date().toISOString(),
message: { content: '', role: MessageRole.User },
},
],
initialConversationId: 'foo',
},
wrapper,
});
});
it('throws an error', (done) => {
try {
const { result } = renderHook(useConversation, {
initialProps: {
chatService: mockChatService,
connectorId: 'my-connector',
initialMessages: [
{
'@timestamp': new Date().toISOString(),
message: { content: '', role: MessageRole.User },
},
],
initialConversationId: 'foo',
},
wrapper,
});

it('throws an error', () => {
expect(() => hookResult.result.current.saveTitle('my-new-title')).toThrow();
result.current.saveTitle('my-new-title');
} catch (e) {
expect(e).toBeInstanceOf(Error);
expect(e.message).toBe('Cannot set initialMessages if initialConversationId is set');
done();
}
});
});

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

import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useLocalStorage } from './use_local_storage';

describe('useLocalStorage', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import React from 'react';

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

import { DocumentProvider, useSelectedDocument } from './document_context';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jest.mock('../../enterprise_search_content/components/search_index/indices/indic

import { setMockValues, mockKibanaValues } from '../../__mocks__/kea_logic';

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

import { EuiSideNavItemType } from '@elastic/eui';

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

import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useKibana } from './use_kibana';
import { useDeleteEndpoint } from './use_delete_endpoint';
Expand Down Expand Up @@ -43,7 +43,7 @@ describe('useDeleteEndpoint', () => {
};

it('should call delete endpoint and show success toast on success', async () => {
const { result, waitFor } = renderHook(() => useDeleteEndpoint(), { wrapper });
const { result } = renderHook(() => useDeleteEndpoint(), { wrapper });

result.current.mutate({ type: 'text_embedding', id: 'in-1' });

Expand All @@ -60,7 +60,7 @@ describe('useDeleteEndpoint', () => {
it('should show error toast on failure', async () => {
const error = { body: { message: 'error' } };
mockDelete.mockRejectedValue(error);
const { result, waitFor } = renderHook(() => useDeleteEndpoint(), { wrapper });
const { result } = renderHook(() => useDeleteEndpoint(), { wrapper });

result.current.mutate({ type: 'model', id: '123' });

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

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

import { useScanUsage } from './use_scan_usage';
import { useKibana } from './use_kibana';
Expand Down Expand Up @@ -43,7 +43,7 @@ describe('useScanUsage', () => {
});

test('should call API endpoint with the correct parameters and return response', async () => {
const { result, waitForNextUpdate } = renderHook(
const { result } = renderHook(
() =>
useScanUsage({
type: 'text_embedding',
Expand All @@ -52,18 +52,18 @@ describe('useScanUsage', () => {
{ wrapper }
);

await waitForNextUpdate();
await waitFor(() => {
expect(mockDelete).toHaveBeenCalledWith(
'/internal/inference_endpoint/endpoints/text_embedding/in-1',
{ query: { scanUsage: true } }
);

expect(mockDelete).toHaveBeenCalledWith(
'/internal/inference_endpoint/endpoints/text_embedding/in-1',
{ query: { scanUsage: true } }
);

expect(result.current.data).toEqual({
acknowledge: true,
error_message: 'inference id is being used',
indexes: ['index1', 'index2'],
pipelines: ['pipeline1', 'pipeline2'],
expect(result.current.data).toEqual({
acknowledge: true,
error_message: 'inference id is being used',
indexes: ['index1', 'index2'],
pipelines: ['pipeline1', 'pipeline2'],
});
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { InferenceAPIConfigResponse } from '@kbn/ml-trained-models-utils';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { QueryParams } from '../components/all_inference_endpoints/types';
import { useTableData } from './use_table_data';
import { INFERENCE_ENDPOINTS_TABLE_PER_PAGE_VALUES } from '../components/all_inference_endpoints/types';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useLoadConnectors } from './use_load_connectors';
import { useLLMsModels } from './use_llms_models';
import { LLMs } from '../types';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { loadAllActions as loadConnectors } from '@kbn/triggers-actions-ui-plugin/public/common/constants';
import { useLoadConnectors } from './use_load_connectors';
import { useKibana } from './use_kibana';
import { act, renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { OpenAiProviderType } from '@kbn/stack-connectors-plugin/common/openai/constants';

const mockedLoadConnectors = loadConnectors as jest.Mock;
Expand Down Expand Up @@ -80,11 +80,9 @@ describe('useLoadConnectors', () => {
];
mockedLoadConnectors.mockResolvedValue(connectors);

await act(async () => {
const { result, waitForNextUpdate } = renderHook(() => useLoadConnectors());
await waitForNextUpdate();

await expect(result.current).resolves.toStrictEqual([
const { result } = renderHook(() => useLoadConnectors());
await waitFor(() =>
expect(result.current).resolves.toStrictEqual([
{
actionTypeId: '.gen-ai',
config: {
Expand Down Expand Up @@ -122,8 +120,8 @@ describe('useLoadConnectors', () => {
title: 'OpenAI Other',
type: 'openai_other',
},
]);
});
])
);
});

it('handles pre-configured connectors', async () => {
Expand All @@ -149,11 +147,9 @@ describe('useLoadConnectors', () => {
];
mockedLoadConnectors.mockResolvedValue(connectors);

await act(async () => {
const { result, waitForNextUpdate } = renderHook(() => useLoadConnectors());
await waitForNextUpdate();

await expect(result.current).resolves.toStrictEqual([
const { result } = renderHook(() => useLoadConnectors());
await waitFor(() =>
expect(result.current).resolves.toStrictEqual([
{
actionTypeId: '.gen-ai',
id: '1',
Expand All @@ -171,22 +167,20 @@ describe('useLoadConnectors', () => {
title: 'OpenAI Azure',
type: 'openai_azure',
},
]);
});
])
);
});

it('handles errors correctly', async () => {
const error = new Error('Test Error');
mockedLoadConnectors.mockRejectedValue(error);

await act(async () => {
const { waitForNextUpdate } = renderHook(() => useLoadConnectors());
await waitForNextUpdate();

renderHook(() => useLoadConnectors());
await waitFor(() =>
expect(mockedUseKibana().services.notifications.toasts.addError).toHaveBeenCalledWith(
error,
expect.any(Object)
);
});
)
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useLoadFieldsByIndices } from './use_load_fields_by_indices';
import { useUsageTracker } from './use_usage_tracker';
import { useIndicesFields } from './use_indices_fields';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useManagementLink } from './use_management_link';
import { useKibana } from './use_kibana';

Expand Down Expand Up @@ -41,13 +41,13 @@ describe('useManagementLink Hook', () => {
'http://localhost:5601/app/management/insightsAndAlerting/triggersActionsConnectors';
mockGetUrl.mockResolvedValue(expectedUrl);
const connectorId = 'test-connector-id';
const { result, waitForNextUpdate } = renderHook(() => useManagementLink(connectorId));
await waitForNextUpdate();

expect(result.current).toBe(expectedUrl);
expect(mockGetUrl).toHaveBeenCalledWith({
sectionId: 'insightsAndAlerting',
appId: 'triggersActionsConnectors/connectors/test-connector-id',
const { result } = renderHook(() => useManagementLink(connectorId));
await waitFor(() => {
expect(result.current).toBe(expectedUrl);
expect(mockGetUrl).toHaveBeenCalledWith({
sectionId: 'insightsAndAlerting',
appId: 'triggersActionsConnectors/connectors/test-connector-id',
});
});
});

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

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useQueryIndices } from './use_query_indices';

jest.mock('./use_kibana', () => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useUsageTracker } from './use_usage_tracker';
import { useController } from 'react-hook-form';
import { useIndicesFields } from './use_indices_fields';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useKibana } from './use_kibana';
import { useUsageTracker } from './use_usage_tracker';

Expand Down

0 comments on commit 90b77c6

Please sign in to comment.