Skip to content

Commit

Permalink
[React18] Migrated test suites to accommodate changes to testing libr…
Browse files Browse the repository at this point in the history
…ary owned by search-kibana
  • Loading branch information
eokoneyo committed Nov 21, 2024
1 parent 51a84eb commit b06da9b
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 b06da9b

Please sign in to comment.