Skip to content

Commit

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

# Backport

This will backport the following commits from `main` to `8.x`:
- [[React18] Migrate test suites to account for testing library upgrades
search-kibana (#201157)](#201157)

<!--- Backport version: 9.4.3 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Eyo O.
Eyo","email":"[email protected]"},"sourceCommit":{"committedDate":"2024-12-16T10:48:13Z","message":"[React18]
Migrate test suites to account for testing library upgrades
search-kibana (#201157)\n\nThis PR migrates test suites that use
`renderHook` from the library\r\n`@testing-library/react-hooks` to adopt
the equivalent and replacement\r\nof `renderHook` from the export that
is now available from\r\n`@testing-library/react`. This work is required
for the planned\r\nmigration to react18.\r\n\r\n## Context\r\n\r\nIn
this PR, usages of `waitForNextUpdate` that previously could
have\r\nbeen destructured from `renderHook` are now been replaced with
`waitFor`\r\nexported from `@testing-library/react`, furthermore
`waitFor`\r\nthat would also have been destructured from the same
renderHook result\r\nis now been replaced with `waitFor` from the export
of\r\n`@testing-library/react`.\r\n\r\n***Why is `waitFor` a sufficient
enough replacement for\r\n`waitForNextUpdate`, and better for testing
values subject to async\r\ncomputations?***\r\n\r\nWaitFor will retry
the provided callback if an error is returned, till\r\nthe configured
timeout elapses. By default the retry interval is `50ms`\r\nwith a
timeout value of `1000ms` that\r\neffectively translates to at least 20
retries for assertions placed\r\nwithin waitFor.
See\r\nhttps://testing-library.com/docs/dom-testing-library/api-async/#waitfor\r\nfor
more information.\r\nThis however means that for person's writing tests,
said person has to\r\nbe explicit about expectations that describe the
internal state of the\r\nhook being tested.\r\nThis implies checking for
instance when a react query hook is being\r\nrendered, there's an
assertion that said hook isn't loading anymore.\r\n\r\nIn this PR you'd
notice that this pattern has been adopted, with most\r\nexisting
assertions following an invocation of `waitForNextUpdate`
being\r\nplaced within a `waitFor`\r\ninvocation. In some cases the
replacement is simply a `waitFor(() => new\r\nPromise((resolve) =>
resolve(null)))` (many thanks to @kapral18, for\r\npoint out exactly why
this works),\r\nwhere this suffices the assertions that follow aren't
placed within a\r\nwaitFor so this PR doesn't get larger than it needs
to be.\r\n\r\nIt's also worth pointing out this PR might also contain
changes to test\r\nand application code to improve said existing
test.\r\n\r\n### What to do next?\r\n1. Review the changes in this
PR.\r\n2. If you think the changes are correct, approve the
PR.\r\n\r\n## Any questions?\r\nIf you have any questions or need help
with this PR, please leave\r\ncomments in this
PR.\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"90b77c6ab3c6fb5d2a2824aca5e91970a623460c","branchLabelMapping":{"^v9.0.0$":"main","^v8.18.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","Team:Search","backport:prev-minor","React@18"],"title":"[React18]
Migrate test suites to account for testing library upgrades
search-kibana","number":201157,"url":"https://github.com/elastic/kibana/pull/201157","mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
search-kibana (#201157)\n\nThis PR migrates test suites that use
`renderHook` from the library\r\n`@testing-library/react-hooks` to adopt
the equivalent and replacement\r\nof `renderHook` from the export that
is now available from\r\n`@testing-library/react`. This work is required
for the planned\r\nmigration to react18.\r\n\r\n## Context\r\n\r\nIn
this PR, usages of `waitForNextUpdate` that previously could
have\r\nbeen destructured from `renderHook` are now been replaced with
`waitFor`\r\nexported from `@testing-library/react`, furthermore
`waitFor`\r\nthat would also have been destructured from the same
renderHook result\r\nis now been replaced with `waitFor` from the export
of\r\n`@testing-library/react`.\r\n\r\n***Why is `waitFor` a sufficient
enough replacement for\r\n`waitForNextUpdate`, and better for testing
values subject to async\r\ncomputations?***\r\n\r\nWaitFor will retry
the provided callback if an error is returned, till\r\nthe configured
timeout elapses. By default the retry interval is `50ms`\r\nwith a
timeout value of `1000ms` that\r\neffectively translates to at least 20
retries for assertions placed\r\nwithin waitFor.
See\r\nhttps://testing-library.com/docs/dom-testing-library/api-async/#waitfor\r\nfor
more information.\r\nThis however means that for person's writing tests,
said person has to\r\nbe explicit about expectations that describe the
internal state of the\r\nhook being tested.\r\nThis implies checking for
instance when a react query hook is being\r\nrendered, there's an
assertion that said hook isn't loading anymore.\r\n\r\nIn this PR you'd
notice that this pattern has been adopted, with most\r\nexisting
assertions following an invocation of `waitForNextUpdate`
being\r\nplaced within a `waitFor`\r\ninvocation. In some cases the
replacement is simply a `waitFor(() => new\r\nPromise((resolve) =>
resolve(null)))` (many thanks to @kapral18, for\r\npoint out exactly why
this works),\r\nwhere this suffices the assertions that follow aren't
placed within a\r\nwaitFor so this PR doesn't get larger than it needs
to be.\r\n\r\nIt's also worth pointing out this PR might also contain
changes to test\r\nand application code to improve said existing
test.\r\n\r\n### What to do next?\r\n1. Review the changes in this
PR.\r\n2. If you think the changes are correct, approve the
PR.\r\n\r\n## Any questions?\r\nIf you have any questions or need help
with this PR, please leave\r\ncomments in this
PR.\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"90b77c6ab3c6fb5d2a2824aca5e91970a623460c"}},"sourceBranch":"main","suggestedTargetBranches":[],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","branchLabelMappingKey":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/201157","number":201157,"mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
search-kibana (#201157)\n\nThis PR migrates test suites that use
`renderHook` from the library\r\n`@testing-library/react-hooks` to adopt
the equivalent and replacement\r\nof `renderHook` from the export that
is now available from\r\n`@testing-library/react`. This work is required
for the planned\r\nmigration to react18.\r\n\r\n## Context\r\n\r\nIn
this PR, usages of `waitForNextUpdate` that previously could
have\r\nbeen destructured from `renderHook` are now been replaced with
`waitFor`\r\nexported from `@testing-library/react`, furthermore
`waitFor`\r\nthat would also have been destructured from the same
renderHook result\r\nis now been replaced with `waitFor` from the export
of\r\n`@testing-library/react`.\r\n\r\n***Why is `waitFor` a sufficient
enough replacement for\r\n`waitForNextUpdate`, and better for testing
values subject to async\r\ncomputations?***\r\n\r\nWaitFor will retry
the provided callback if an error is returned, till\r\nthe configured
timeout elapses. By default the retry interval is `50ms`\r\nwith a
timeout value of `1000ms` that\r\neffectively translates to at least 20
retries for assertions placed\r\nwithin waitFor.
See\r\nhttps://testing-library.com/docs/dom-testing-library/api-async/#waitfor\r\nfor
more information.\r\nThis however means that for person's writing tests,
said person has to\r\nbe explicit about expectations that describe the
internal state of the\r\nhook being tested.\r\nThis implies checking for
instance when a react query hook is being\r\nrendered, there's an
assertion that said hook isn't loading anymore.\r\n\r\nIn this PR you'd
notice that this pattern has been adopted, with most\r\nexisting
assertions following an invocation of `waitForNextUpdate`
being\r\nplaced within a `waitFor`\r\ninvocation. In some cases the
replacement is simply a `waitFor(() => new\r\nPromise((resolve) =>
resolve(null)))` (many thanks to @kapral18, for\r\npoint out exactly why
this works),\r\nwhere this suffices the assertions that follow aren't
placed within a\r\nwaitFor so this PR doesn't get larger than it needs
to be.\r\n\r\nIt's also worth pointing out this PR might also contain
changes to test\r\nand application code to improve said existing
test.\r\n\r\n### What to do next?\r\n1. Review the changes in this
PR.\r\n2. If you think the changes are correct, approve the
PR.\r\n\r\n## Any questions?\r\nIf you have any questions or need help
with this PR, please leave\r\ncomments in this
PR.\r\n\r\nCo-authored-by: Elastic Machine
<[email protected]>","sha":"90b77c6ab3c6fb5d2a2824aca5e91970a623460c"}}]}]
BACKPORT-->

Co-authored-by: Eyo O. Eyo <[email protected]>
  • Loading branch information
kibanamachine and eokoneyo authored Dec 16, 2024
1 parent 1ac650b commit e1438df
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 e1438df

Please sign in to comment.