[React18] Migrate test suites to account for testing library upgrades security-generative-ai (#201160)

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-12-12 06:21:20 +01:00 committed by GitHub
parent 0f160ab616
commit 6ece92e9e1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
35 changed files with 402 additions and 421 deletions

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
@ -41,9 +41,7 @@ describe('useFetchAnonymizationFields', () => {
wrapper: createWrapper(), wrapper: createWrapper(),
}); });
await act(async () => { await waitFor(() => {
const { waitForNextUpdate } = renderHook(() => useFetchAnonymizationFields());
await waitForNextUpdate();
expect(http.fetch).toHaveBeenCalledWith( expect(http.fetch).toHaveBeenCalledWith(
'/api/security_ai_assistant/anonymization_fields/_find', '/api/security_ai_assistant/anonymization_fields/_find',
{ {

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { renderHook } from '@testing-library/react-hooks'; import { renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { act, waitFor, renderHook } from '@testing-library/react';
import { import {
DeleteConversationParams, DeleteConversationParams,
@ -32,18 +32,18 @@ describe('conversations api', () => {
await act(async () => { await act(async () => {
const deleteProps = { http, toasts, id: 'test' } as unknown as DeleteConversationParams; const deleteProps = { http, toasts, id: 'test' } as unknown as DeleteConversationParams;
const { waitForNextUpdate } = renderHook(() => deleteConversation(deleteProps)); renderHook(() => deleteConversation(deleteProps));
await waitForNextUpdate(); await waitFor(() => {
expect(deleteProps.http.fetch).toHaveBeenCalledWith(
expect(deleteProps.http.fetch).toHaveBeenCalledWith( '/api/security_ai_assistant/current_user/conversations/test',
'/api/security_ai_assistant/current_user/conversations/test', {
{ method: 'DELETE',
method: 'DELETE', signal: undefined,
signal: undefined, version: '2023-10-31',
version: '2023-10-31', }
} );
); expect(toasts.addError).not.toHaveBeenCalled();
expect(toasts.addError).not.toHaveBeenCalled(); });
}); });
}); });
@ -58,18 +58,18 @@ describe('conversations api', () => {
it('should call api to get conversation', async () => { it('should call api to get conversation', async () => {
await act(async () => { await act(async () => {
const getProps = { http, toasts, id: 'test' } as unknown as GetConversationByIdParams; const getProps = { http, toasts, id: 'test' } as unknown as GetConversationByIdParams;
const { waitForNextUpdate } = renderHook(() => getConversationById(getProps)); renderHook(() => getConversationById(getProps));
await waitForNextUpdate(); await waitFor(() => {
expect(getProps.http.fetch).toHaveBeenCalledWith(
expect(getProps.http.fetch).toHaveBeenCalledWith( '/api/security_ai_assistant/current_user/conversations/test',
'/api/security_ai_assistant/current_user/conversations/test', {
{ method: 'GET',
method: 'GET', signal: undefined,
signal: undefined, version: '2023-10-31',
version: '2023-10-31', }
} );
); expect(toasts.addError).not.toHaveBeenCalled();
expect(toasts.addError).not.toHaveBeenCalled(); });
}); });
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
@ -41,11 +41,7 @@ describe('useFetchCurrentUserConversations', () => {
wrapper: createWrapper(), wrapper: createWrapper(),
}); });
await act(async () => { await waitFor(() => {
const { waitForNextUpdate } = renderHook(() =>
useFetchCurrentUserConversations(defaultProps)
);
await waitForNextUpdate();
expect(defaultProps.http.fetch).toHaveBeenCalledWith( expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/api/security_ai_assistant/current_user/conversations/_find', '/api/security_ai_assistant/current_user/conversations/_find',
{ {

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook } from '@testing-library/react';
import { usePerformEvaluation, UsePerformEvaluationParams } from './use_perform_evaluation'; import { usePerformEvaluation, UsePerformEvaluationParams } from './use_perform_evaluation';
import { postEvaluation as _postEvaluation } from './evaluate'; import { postEvaluation as _postEvaluation } from './evaluate';
import { useMutation as _useMutation } from '@tanstack/react-query'; import { useMutation as _useMutation } from '@tanstack/react-query';
@ -50,10 +50,8 @@ describe('usePerformEvaluation', () => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
it('should call api with undefined evalParams', async () => { it('should call api with undefined evalParams', async () => {
await act(async () => { renderHook(() => usePerformEvaluation(defaultProps));
const { waitForNextUpdate } = renderHook(() => usePerformEvaluation(defaultProps)); await waitFor(() => {
await waitForNextUpdate();
expect(defaultProps.http.post).toHaveBeenCalledWith('/internal/elastic_assistant/evaluate', { expect(defaultProps.http.post).toHaveBeenCalledWith('/internal/elastic_assistant/evaluate', {
body: undefined, body: undefined,
headers: { headers: {
@ -80,10 +78,9 @@ describe('usePerformEvaluation', () => {
opts.onError(e); opts.onError(e);
} }
}); });
await act(async () => {
const { waitForNextUpdate } = renderHook(() => usePerformEvaluation(defaultProps));
await waitForNextUpdate();
renderHook(() => usePerformEvaluation(defaultProps));
await waitFor(() =>
expect(defaultProps.http.post).toHaveBeenCalledWith('/internal/elastic_assistant/evaluate', { expect(defaultProps.http.post).toHaveBeenCalledWith('/internal/elastic_assistant/evaluate', {
body: '{"graphs":["d","c"],"datasetName":"kewl","connectorIds":["h","g"],"runName":"test run"}', body: '{"graphs":["d","c"],"datasetName":"kewl","connectorIds":["h","g"],"runName":"test run"}',
headers: { headers: {
@ -91,26 +88,19 @@ describe('usePerformEvaluation', () => {
}, },
signal: undefined, signal: undefined,
version: API_VERSIONS.internal.v1, version: API_VERSIONS.internal.v1,
}); })
}); );
}); });
it('should return evaluation response', async () => { it('should return evaluation response', async () => {
await act(async () => { const { result } = renderHook(() => usePerformEvaluation(defaultProps));
const { result, waitForNextUpdate } = renderHook(() => usePerformEvaluation(defaultProps)); await waitFor(() => expect(result.current).resolves.toStrictEqual(statusResponse));
await waitForNextUpdate();
await expect(result.current).resolves.toStrictEqual(statusResponse);
});
}); });
it('should display error toast when api throws error', async () => { it('should display error toast when api throws error', async () => {
postEvaluationMock.mockRejectedValue(new Error('this is an error')); postEvaluationMock.mockRejectedValue(new Error('this is an error'));
await act(async () => {
const { waitForNextUpdate } = renderHook(() => usePerformEvaluation(defaultProps));
await waitForNextUpdate();
expect(toasts.addError).toHaveBeenCalled(); renderHook(() => usePerformEvaluation(defaultProps));
}); await waitFor(() => expect(toasts.addError).toHaveBeenCalled());
}); });
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook } from '@testing-library/react';
import { import {
useKnowledgeBaseIndices, useKnowledgeBaseIndices,
UseKnowledgeBaseIndicesParams, UseKnowledgeBaseIndicesParams,
@ -48,10 +48,8 @@ describe('useKnowledgeBaseIndices', () => {
}); });
it('should call api to get knowledge base indices', async () => { it('should call api to get knowledge base indices', async () => {
await act(async () => { renderHook(() => useKnowledgeBaseIndices(defaultProps));
const { waitForNextUpdate } = renderHook(() => useKnowledgeBaseIndices(defaultProps)); await waitFor(() => {
await waitForNextUpdate();
expect(defaultProps.http.fetch).toHaveBeenCalledWith( expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/knowledge_base/_indices', '/internal/elastic_assistant/knowledge_base/_indices',
{ {
@ -65,20 +63,17 @@ describe('useKnowledgeBaseIndices', () => {
}); });
it('should return indices response', async () => { it('should return indices response', async () => {
await act(async () => { const { result } = renderHook(() => useKnowledgeBaseIndices(defaultProps));
const { result, waitForNextUpdate } = renderHook(() => useKnowledgeBaseIndices(defaultProps)); await waitFor(() => {
await waitForNextUpdate(); expect(result.current).resolves.toStrictEqual(indicesResponse);
await expect(result.current).resolves.toStrictEqual(indicesResponse);
}); });
}); });
it('should display error toast when api throws error', async () => { it('should display error toast when api throws error', async () => {
getKnowledgeBaseIndicesMock.mockRejectedValue(new Error('this is an error')); getKnowledgeBaseIndicesMock.mockRejectedValue(new Error('this is an error'));
await act(async () => {
const { waitForNextUpdate } = renderHook(() => useKnowledgeBaseIndices(defaultProps));
await waitForNextUpdate();
renderHook(() => useKnowledgeBaseIndices(defaultProps));
await waitFor(() => {
expect(toasts.addError).toHaveBeenCalled(); expect(toasts.addError).toHaveBeenCalled();
}); });
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook } from '@testing-library/react';
import { useKnowledgeBaseStatus, UseKnowledgeBaseStatusParams } from './use_knowledge_base_status'; import { useKnowledgeBaseStatus, UseKnowledgeBaseStatusParams } from './use_knowledge_base_status';
import { getKnowledgeBaseStatus as _getKnowledgeBaseStatus } from './api'; import { getKnowledgeBaseStatus as _getKnowledgeBaseStatus } from './api';
@ -49,10 +49,8 @@ describe('useKnowledgeBaseStatus', () => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
it('should call api to get knowledge base status without resource arg', async () => { it('should call api to get knowledge base status without resource arg', async () => {
await act(async () => { renderHook(() => useKnowledgeBaseStatus(defaultProps));
const { waitForNextUpdate } = renderHook(() => useKnowledgeBaseStatus(defaultProps)); await waitFor(() => {
await waitForNextUpdate();
expect(defaultProps.http.fetch).toHaveBeenCalledWith( expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/knowledge_base/', '/internal/elastic_assistant/knowledge_base/',
{ {
@ -65,12 +63,8 @@ describe('useKnowledgeBaseStatus', () => {
}); });
}); });
it('should call api to get knowledge base status with resource arg', async () => { it('should call api to get knowledge base status with resource arg', async () => {
await act(async () => { renderHook(() => useKnowledgeBaseStatus({ ...defaultProps, resource: 'something' }));
const { waitForNextUpdate } = renderHook(() => await waitFor(() =>
useKnowledgeBaseStatus({ ...defaultProps, resource: 'something' })
);
await waitForNextUpdate();
expect(defaultProps.http.fetch).toHaveBeenCalledWith( expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/knowledge_base/something', '/internal/elastic_assistant/knowledge_base/something',
{ {
@ -78,26 +72,18 @@ describe('useKnowledgeBaseStatus', () => {
signal: undefined, signal: undefined,
version: '1', version: '1',
} }
); )
}); );
}); });
it('should return status response', async () => { it('should return status response', async () => {
await act(async () => { const { result } = renderHook(() => useKnowledgeBaseStatus(defaultProps));
const { result, waitForNextUpdate } = renderHook(() => useKnowledgeBaseStatus(defaultProps)); await waitFor(() => expect(result.current).resolves.toStrictEqual(statusResponse));
await waitForNextUpdate();
await expect(result.current).resolves.toStrictEqual(statusResponse);
});
}); });
it('should display error toast when api throws error', async () => { it('should display error toast when api throws error', async () => {
getKnowledgeBaseStatusMock.mockRejectedValue(new Error('this is an error')); getKnowledgeBaseStatusMock.mockRejectedValue(new Error('this is an error'));
await act(async () => { renderHook(() => useKnowledgeBaseStatus(defaultProps));
const { waitForNextUpdate } = renderHook(() => useKnowledgeBaseStatus(defaultProps)); await waitFor(() => expect(toasts.addError).toHaveBeenCalled());
await waitForNextUpdate();
expect(toasts.addError).toHaveBeenCalled();
});
}); });
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook } from '@testing-library/react';
import { useSetupKnowledgeBase, UseSetupKnowledgeBaseParams } from './use_setup_knowledge_base'; import { useSetupKnowledgeBase, UseSetupKnowledgeBaseParams } from './use_setup_knowledge_base';
import { postKnowledgeBase as _postKnowledgeBase } from './api'; import { postKnowledgeBase as _postKnowledgeBase } from './api';
import { useMutation as _useMutation } from '@tanstack/react-query'; import { useMutation as _useMutation } from '@tanstack/react-query';
@ -50,10 +50,8 @@ describe('useSetupKnowledgeBase', () => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
it('should call api to post knowledge base setup', async () => { it('should call api to post knowledge base setup', async () => {
await act(async () => { renderHook(() => useSetupKnowledgeBase(defaultProps));
const { waitForNextUpdate } = renderHook(() => useSetupKnowledgeBase(defaultProps)); await waitFor(() => {
await waitForNextUpdate();
expect(defaultProps.http.fetch).toHaveBeenCalledWith( expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/knowledge_base/', '/internal/elastic_assistant/knowledge_base/',
{ {
@ -73,36 +71,27 @@ describe('useSetupKnowledgeBase', () => {
opts.onError(e); opts.onError(e);
} }
}); });
await act(async () => {
const { waitForNextUpdate } = renderHook(() => useSetupKnowledgeBase(defaultProps));
await waitForNextUpdate();
renderHook(() => useSetupKnowledgeBase(defaultProps));
await waitFor(() =>
expect(defaultProps.http.fetch).toHaveBeenCalledWith( expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/knowledge_base/something', '/internal/elastic_assistant/knowledge_base/something',
{ {
method: 'POST', method: 'POST',
version: '1', version: '1',
} }
); )
}); );
}); });
it('should return setup response', async () => { it('should return setup response', async () => {
await act(async () => { const { result } = renderHook(() => useSetupKnowledgeBase(defaultProps));
const { result, waitForNextUpdate } = renderHook(() => useSetupKnowledgeBase(defaultProps)); await waitFor(() => expect(result.current).resolves.toStrictEqual(statusResponse));
await waitForNextUpdate();
await expect(result.current).resolves.toStrictEqual(statusResponse);
});
}); });
it('should display error toast when api throws error', async () => { it('should display error toast when api throws error', async () => {
postKnowledgeBaseMock.mockRejectedValue(new Error('this is an error')); postKnowledgeBaseMock.mockRejectedValue(new Error('this is an error'));
await act(async () => { renderHook(() => useSetupKnowledgeBase(defaultProps));
const { waitForNextUpdate } = renderHook(() => useSetupKnowledgeBase(defaultProps)); await waitFor(() => expect(toasts.addError).toHaveBeenCalled());
await waitForNextUpdate();
expect(toasts.addError).toHaveBeenCalled();
});
}); });
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react'; import type { ReactNode } from 'react';
@ -41,9 +41,7 @@ describe('useFetchPrompts', () => {
wrapper: createWrapper(), wrapper: createWrapper(),
}); });
await act(async () => { await waitFor(() => {
const { waitForNextUpdate } = renderHook(() => useFetchPrompts());
await waitForNextUpdate();
expect(http.fetch).toHaveBeenCalledWith('/api/security_ai_assistant/prompts/_find', { expect(http.fetch).toHaveBeenCalledWith('/api/security_ai_assistant/prompts/_find', {
method: 'GET', method: 'GET',
query: { query: {

View file

@ -10,8 +10,7 @@ import { useSendMessage } from '../use_send_message';
import { useConversation } from '../use_conversation'; import { useConversation } from '../use_conversation';
import { emptyWelcomeConvo, welcomeConvo } from '../../mock/conversation'; import { emptyWelcomeConvo, welcomeConvo } from '../../mock/conversation';
import { useChatSend, UseChatSendProps } from './use_chat_send'; import { useChatSend, UseChatSendProps } from './use_chat_send';
import { act, renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook, act } from '@testing-library/react';
import { waitFor } from '@testing-library/react';
import { TestProviders } from '../../mock/test_providers/test_providers'; import { TestProviders } from '../../mock/test_providers/test_providers';
import { useAssistantContext } from '../../..'; import { useAssistantContext } from '../../..';
@ -64,10 +63,10 @@ describe('use chat send', () => {
}); });
it('handleOnChatCleared clears the conversation', async () => { it('handleOnChatCleared clears the conversation', async () => {
(clearConversation as jest.Mock).mockReturnValueOnce(testProps.currentConversation); (clearConversation as jest.Mock).mockReturnValueOnce(testProps.currentConversation);
const { result, waitForNextUpdate } = renderHook(() => useChatSend(testProps), { const { result } = renderHook(() => useChatSend(testProps), {
wrapper: TestProviders, wrapper: TestProviders,
}); });
await waitForNextUpdate(); await waitFor(() => new Promise((resolve) => resolve(null)));
act(() => { act(() => {
result.current.handleOnChatCleared(); result.current.handleOnChatCleared();
}); });
@ -99,7 +98,7 @@ describe('use chat send', () => {
}); });
}); });
it('handleRegenerateResponse removes the last message of the conversation, resends the convo to GenAI, and appends the message received', async () => { it('handleRegenerateResponse removes the last message of the conversation, resends the convo to GenAI, and appends the message received', async () => {
const { result, waitForNextUpdate } = renderHook( const { result } = renderHook(
() => () =>
useChatSend({ ...testProps, currentConversation: { ...welcomeConvo, id: 'welcome-id' } }), useChatSend({ ...testProps, currentConversation: { ...welcomeConvo, id: 'welcome-id' } }),
{ {
@ -107,7 +106,7 @@ describe('use chat send', () => {
} }
); );
await waitForNextUpdate(); await waitFor(() => new Promise((resolve) => resolve(null)));
act(() => { act(() => {
result.current.handleRegenerateResponse(); result.current.handleRegenerateResponse();
}); });
@ -121,10 +120,10 @@ describe('use chat send', () => {
}); });
it('sends telemetry events for both user and assistant', async () => { it('sends telemetry events for both user and assistant', async () => {
const promptText = 'prompt text'; const promptText = 'prompt text';
const { result, waitForNextUpdate } = renderHook(() => useChatSend(testProps), { const { result } = renderHook(() => useChatSend(testProps), {
wrapper: TestProviders, wrapper: TestProviders,
}); });
await waitForNextUpdate(); await waitFor(() => new Promise((resolve) => resolve(null)));
act(() => { act(() => {
result.current.handleChatSend(promptText); result.current.handleChatSend(promptText);
}); });

View file

@ -4,7 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License
* 2.0. * 2.0.
*/ */
import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useConversationChanged } from './use_conversation_changed'; import { useConversationChanged } from './use_conversation_changed';
import { customConvo } from '../../../mock/conversation'; import { customConvo } from '../../../mock/conversation';
import { mockConnectors } from '../../../mock/connectors'; import { mockConnectors } from '../../../mock/connectors';

View file

@ -4,7 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License
* 2.0. * 2.0.
*/ */
import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useConversationDeleted } from './use_conversation_deleted'; import { useConversationDeleted } from './use_conversation_deleted';
import { customConvo, alertConvo, welcomeConvo } from '../../../mock/conversation'; import { customConvo, alertConvo, welcomeConvo } from '../../../mock/conversation';
import { Conversation, ConversationsBulkActions } from '../../../..'; import { Conversation, ConversationsBulkActions } from '../../../..';

View file

@ -4,7 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License
* 2.0. * 2.0.
*/ */
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { import {
useConversationsTable, useConversationsTable,
GetConversationsListParams, GetConversationsListParams,

View file

@ -4,7 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License
* 2.0. * 2.0.
*/ */
import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useSystemPromptEditor } from './use_system_prompt_editor'; import { useSystemPromptEditor } from './use_system_prompt_editor';
import { import {
mockSystemPrompt, mockSystemPrompt,

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { renderHook } from '@testing-library/react-hooks'; import { renderHook } from '@testing-library/react';
import { useSystemPromptTable } from './use_system_prompt_table'; import { useSystemPromptTable } from './use_system_prompt_table';
import { Conversation } from '../../../../assistant_context/types'; import { Conversation } from '../../../../assistant_context/types';
import { AIConnector } from '../../../../connectorland/connector_selector'; import { AIConnector } from '../../../../connectorland/connector_selector';

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { renderHook, act } from '@testing-library/react-hooks'; import { renderHook, act } from '@testing-library/react';
import { useQuickPromptEditor } from './use_quick_prompt_editor'; import { useQuickPromptEditor } from './use_quick_prompt_editor';
import { mockAlertPromptContext } from '../../../mock/prompt_context'; import { mockAlertPromptContext } from '../../../mock/prompt_context';
import { MOCK_QUICK_PROMPTS } from '../../../mock/quick_prompt'; import { MOCK_QUICK_PROMPTS } from '../../../mock/quick_prompt';

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { renderHook } from '@testing-library/react-hooks'; import { renderHook } from '@testing-library/react';
import { useQuickPromptTable } from './use_quick_prompt_table'; import { useQuickPromptTable } from './use_quick_prompt_table';
import { EuiTableActionsColumnType, EuiTableComputedColumnType } from '@elastic/eui'; import { EuiTableActionsColumnType, EuiTableComputedColumnType } from '@elastic/eui';
import { MOCK_QUICK_PROMPTS } from '../../../mock/quick_prompt'; import { MOCK_QUICK_PROMPTS } from '../../../mock/quick_prompt';

View file

@ -4,7 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { DEFAULT_LATEST_ALERTS } from '../../../assistant_context/constants'; import { DEFAULT_LATEST_ALERTS } from '../../../assistant_context/constants';
import { alertConvo, welcomeConvo } from '../../../mock/conversation'; import { alertConvo, welcomeConvo } from '../../../mock/conversation';
@ -98,96 +99,101 @@ describe('useSettingsUpdater', () => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
it('should set all state variables to their initial values when resetSettings is called', async () => { it('should set all state variables to their initial values when resetSettings is called', async () => {
await act(async () => { const { result } = renderHook(() =>
const { result, waitForNextUpdate } = renderHook(() => useSettingsUpdater(
useSettingsUpdater( mockConversations,
mockConversations, {
{ data: [...mockSystemPrompts, ...mockQuickPrompts],
data: [...mockSystemPrompts, ...mockQuickPrompts], page: 1,
page: 1, perPage: 100,
perPage: 100, total: 10,
total: 10, },
}, conversationsLoaded,
conversationsLoaded, promptsLoaded,
promptsLoaded, anonymizationFields
anonymizationFields )
) );
); await waitFor(() => new Promise((resolve) => resolve(null)));
await waitForNextUpdate(); const {
const { setConversationSettings,
setConversationSettings, setConversationsSettingsBulkActions,
setConversationsSettingsBulkActions, setUpdatedKnowledgeBaseSettings,
setUpdatedKnowledgeBaseSettings, setUpdatedAssistantStreamingEnabled,
setUpdatedAssistantStreamingEnabled, resetSettings,
resetSettings, setPromptsBulkActions,
setPromptsBulkActions, } = result.current;
} = result.current;
act(() => {
setConversationSettings(updatedValues.conversations); setConversationSettings(updatedValues.conversations);
setConversationsSettingsBulkActions({}); setConversationsSettingsBulkActions({});
setPromptsBulkActions({}); setPromptsBulkActions({});
setUpdatedAnonymizationData(updatedValues.updatedAnonymizationData); setUpdatedAnonymizationData(updatedValues.updatedAnonymizationData);
setUpdatedKnowledgeBaseSettings(updatedValues.knowledgeBase); setUpdatedKnowledgeBaseSettings(updatedValues.knowledgeBase);
setUpdatedAssistantStreamingEnabled(updatedValues.assistantStreamingEnabled); setUpdatedAssistantStreamingEnabled(updatedValues.assistantStreamingEnabled);
expect(result.current.conversationSettings).toEqual(updatedValues.conversations);
expect(result.current.quickPromptSettings).toEqual(updatedValues.allQuickPrompts);
expect(result.current.systemPromptSettings).toEqual(updatedValues.allSystemPrompts);
expect(result.current.updatedAnonymizationData).toEqual(anonymizationFields);
expect(result.current.knowledgeBase).toEqual(updatedValues.knowledgeBase);
expect(result.current.assistantStreamingEnabled).toEqual(
updatedValues.assistantStreamingEnabled
);
resetSettings();
expect(result.current.conversationSettings).toEqual(mockConversations);
expect(result.current.quickPromptSettings).toEqual(mockValues.allQuickPrompts);
expect(result.current.systemPromptSettings).toEqual(mockValues.allSystemPrompts);
expect(result.current.anonymizationFieldsBulkActions).toEqual(
mockValues.anonymizationFieldsBulkActions
);
expect(result.current.knowledgeBase).toEqual(mockValues.knowledgeBase);
expect(result.current.assistantStreamingEnabled).toEqual(
mockValues.assistantStreamingEnabled
);
}); });
expect(result.current.conversationSettings).toEqual(updatedValues.conversations);
expect(result.current.quickPromptSettings).toEqual(updatedValues.allQuickPrompts);
expect(result.current.systemPromptSettings).toEqual(updatedValues.allSystemPrompts);
expect(result.current.updatedAnonymizationData).toEqual(anonymizationFields);
expect(result.current.knowledgeBase).toEqual(updatedValues.knowledgeBase);
expect(result.current.assistantStreamingEnabled).toEqual(
updatedValues.assistantStreamingEnabled
);
act(() => {
resetSettings();
});
expect(result.current.conversationSettings).toEqual(mockConversations);
expect(result.current.quickPromptSettings).toEqual(mockValues.allQuickPrompts);
expect(result.current.systemPromptSettings).toEqual(mockValues.allSystemPrompts);
expect(result.current.anonymizationFieldsBulkActions).toEqual(
mockValues.anonymizationFieldsBulkActions
);
expect(result.current.knowledgeBase).toEqual(mockValues.knowledgeBase);
expect(result.current.assistantStreamingEnabled).toEqual(mockValues.assistantStreamingEnabled);
}); });
it('should update all state variables to their updated values when saveSettings is called', async () => { it('should update all state variables to their updated values when saveSettings is called', async () => {
await act(async () => { const { result } = renderHook(() =>
const { result, waitForNextUpdate } = renderHook(() => useSettingsUpdater(
useSettingsUpdater( mockConversations,
mockConversations, {
{ data: mockSystemPrompts,
data: mockSystemPrompts, page: 1,
page: 1, perPage: 100,
perPage: 100, total: 10,
total: 10, },
}, conversationsLoaded,
conversationsLoaded, promptsLoaded,
promptsLoaded, anonymizationFields
anonymizationFields )
) );
); await waitFor(() => new Promise((resolve) => resolve(null)));
await waitForNextUpdate();
const {
setConversationSettings,
setConversationsSettingsBulkActions,
setAnonymizationFieldsBulkActions,
setUpdatedKnowledgeBaseSettings,
setPromptsBulkActions,
} = result.current;
const {
setConversationSettings,
setConversationsSettingsBulkActions,
setAnonymizationFieldsBulkActions,
setUpdatedKnowledgeBaseSettings,
setPromptsBulkActions,
} = result.current;
act(() => {
setConversationSettings(updatedValues.conversations); setConversationSettings(updatedValues.conversations);
setConversationsSettingsBulkActions({ delete: { ids: ['1'] } }); setConversationsSettingsBulkActions({ delete: { ids: ['1'] } });
setAnonymizationFieldsBulkActions({ delete: { ids: ['1'] } }); setAnonymizationFieldsBulkActions({ delete: { ids: ['1'] } });
setPromptsBulkActions({}); setPromptsBulkActions({});
setUpdatedAnonymizationData(updatedValues.updatedAnonymizationData); setUpdatedAnonymizationData(updatedValues.updatedAnonymizationData);
setUpdatedKnowledgeBaseSettings(updatedValues.knowledgeBase); setUpdatedKnowledgeBaseSettings(updatedValues.knowledgeBase);
});
await act(async () => {
await result.current.saveSettings(); await result.current.saveSettings();
});
await waitFor(() => {
expect(mockHttp.fetch).toHaveBeenCalledWith( expect(mockHttp.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/current_user/conversations/_bulk_action', '/internal/elastic_assistant/current_user/conversations/_bulk_action',
{ {
@ -202,80 +208,99 @@ describe('useSettingsUpdater', () => {
expect(setKnowledgeBaseMock).toHaveBeenCalledWith(updatedValues.knowledgeBase); expect(setKnowledgeBaseMock).toHaveBeenCalledWith(updatedValues.knowledgeBase);
}); });
}); });
it('should track when alerts count is updated', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook(() =>
useSettingsUpdater(
mockConversations,
{
data: mockSystemPrompts,
page: 1,
perPage: 100,
total: 10,
},
conversationsLoaded,
promptsLoaded,
anonymizationFields
)
);
await waitForNextUpdate();
const { setUpdatedKnowledgeBaseSettings } = result.current;
it('should track when alerts count is updated', async () => {
const { result } = renderHook(() =>
useSettingsUpdater(
mockConversations,
{
data: mockSystemPrompts,
page: 1,
perPage: 100,
total: 10,
},
conversationsLoaded,
promptsLoaded,
anonymizationFields
)
);
await waitFor(() => new Promise((resolve) => resolve(null)));
const { setUpdatedKnowledgeBaseSettings } = result.current;
act(() => {
setUpdatedKnowledgeBaseSettings({ setUpdatedKnowledgeBaseSettings({
...updatedValues.knowledgeBase, ...updatedValues.knowledgeBase,
}); });
await result.current.saveSettings();
expect(reportAssistantSettingToggled).toHaveBeenCalledWith({ alertsCountUpdated: true });
}); });
});
it('should track when streaming is updated', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook(() =>
useSettingsUpdater(
mockConversations,
{
data: mockSystemPrompts,
page: 1,
perPage: 100,
total: 10,
},
conversationsLoaded,
promptsLoaded,
anonymizationFields
)
);
await waitForNextUpdate();
const { setUpdatedAssistantStreamingEnabled } = result.current;
setUpdatedAssistantStreamingEnabled(false); await act(async () => {
await result.current.saveSettings(); await result.current.saveSettings();
});
await waitFor(() =>
expect(reportAssistantSettingToggled).toHaveBeenCalledWith({ alertsCountUpdated: true })
);
});
it('should track when streaming is updated', async () => {
const { result } = renderHook(() =>
useSettingsUpdater(
mockConversations,
{
data: mockSystemPrompts,
page: 1,
perPage: 100,
total: 10,
},
conversationsLoaded,
promptsLoaded,
anonymizationFields
)
);
await waitFor(() => new Promise((resolve) => resolve(null)));
const { setUpdatedAssistantStreamingEnabled } = result.current;
act(() => {
setUpdatedAssistantStreamingEnabled(false);
});
await act(async () => {
await result.current.saveSettings();
});
await waitFor(() =>
expect(reportAssistantSettingToggled).toHaveBeenCalledWith({ expect(reportAssistantSettingToggled).toHaveBeenCalledWith({
assistantStreamingEnabled: false, assistantStreamingEnabled: false,
}); })
}); );
}); });
it('if no settings update, do not track anything', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook(() =>
useSettingsUpdater(
mockConversations,
{
data: mockSystemPrompts,
page: 1,
perPage: 100,
total: 10,
},
conversationsLoaded,
promptsLoaded,
anonymizationFields
)
);
await waitForNextUpdate();
const { setUpdatedKnowledgeBaseSettings } = result.current;
it('if no settings update, do not track anything', async () => {
const { result } = renderHook(() =>
useSettingsUpdater(
mockConversations,
{
data: mockSystemPrompts,
page: 1,
perPage: 100,
total: 10,
},
conversationsLoaded,
promptsLoaded,
anonymizationFields
)
);
await waitFor(() => new Promise((resolve) => resolve(null)));
const { setUpdatedKnowledgeBaseSettings } = result.current;
await act(async () => {
setUpdatedKnowledgeBaseSettings(mockValues.knowledgeBase); setUpdatedKnowledgeBaseSettings(mockValues.knowledgeBase);
await result.current.saveSettings(); await result.current.saveSettings();
expect(reportAssistantSettingToggled).not.toHaveBeenCalledWith();
}); });
await waitFor(() => expect(reportAssistantSettingToggled).not.toHaveBeenCalledWith());
}); });
}); });

View file

@ -5,11 +5,10 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks';
import { DefinedUseQueryResult } from '@tanstack/react-query'; import { DefinedUseQueryResult } from '@tanstack/react-query';
import { useAssistantOverlay } from '.'; import { useAssistantOverlay } from '.';
import { waitFor } from '@testing-library/react'; import { waitFor, renderHook, act } from '@testing-library/react';
import { useFetchCurrentUserConversations } from '../api'; import { useFetchCurrentUserConversations } from '../api';
import { Conversation } from '../../assistant_context/types'; import { Conversation } from '../../assistant_context/types';
import { mockConnectors } from '../../mock/connectors'; import { mockConnectors } from '../../mock/connectors';

View file

@ -6,7 +6,7 @@
*/ */
import { useConversation } from '.'; import { useConversation } from '.';
import { act, renderHook } from '@testing-library/react-hooks'; import { act, waitFor, renderHook } from '@testing-library/react';
import { TestProviders } from '../../mock/test_providers/test_providers'; import { TestProviders } from '../../mock/test_providers/test_providers';
import React from 'react'; import React from 'react';
import { MessageRole } from '@kbn/elastic-assistant-common'; import { MessageRole } from '@kbn/elastic-assistant-common';
@ -54,79 +54,86 @@ describe('useConversation', () => {
}); });
it('should create a new conversation when called with valid conversationId and message', async () => { it('should create a new conversation when called with valid conversationId and message', async () => {
await act(async () => { const { result } = renderHook(() => useConversation(), {
const { result, waitForNextUpdate } = renderHook(() => useConversation(), { wrapper: ({ children }: React.PropsWithChildren<{}>) => (
wrapper: ({ children }: React.PropsWithChildren<{}>) => ( <TestProviders providerContext={{ http: httpMock }}>{children}</TestProviders>
<TestProviders providerContext={{ http: httpMock }}>{children}</TestProviders> ),
), });
});
await waitForNextUpdate();
createConversation.mockResolvedValue(mockConvo);
const createResult = await result.current.createConversation({ await waitFor(() => new Promise((resolve) => resolve(null)));
createConversation.mockResolvedValue(mockConvo);
let createResult;
await act(async () => {
createResult = await result.current.createConversation({
...mockConvo, ...mockConvo,
replacements: {}, replacements: {},
title: mockConvo.title, title: mockConvo.title,
category: 'assistant', category: 'assistant',
}); });
expect(createResult).toEqual(mockConvo);
}); });
expect(createResult).toEqual(mockConvo);
}); });
it('should delete an existing conversation when called with valid conversationId', async () => { it('should delete an existing conversation when called with valid conversationId', async () => {
const { result } = renderHook(() => useConversation(), {
wrapper: ({ children }: React.PropsWithChildren<{}>) => (
<TestProviders providerContext={{ http: httpMock }}>{children}</TestProviders>
),
});
await waitFor(() => new Promise((resolve) => resolve(null)));
await act(async () => { await act(async () => {
const { result, waitForNextUpdate } = renderHook(() => useConversation(), {
wrapper: ({ children }: React.PropsWithChildren<{}>) => (
<TestProviders providerContext={{ http: httpMock }}>{children}</TestProviders>
),
});
await waitForNextUpdate();
await result.current.deleteConversation('new-convo'); await result.current.deleteConversation('new-convo');
});
expect(deleteConversation).toHaveBeenCalledWith({ expect(deleteConversation).toHaveBeenCalledWith({
http: httpMock, http: httpMock,
id: 'new-convo', id: 'new-convo',
});
}); });
}); });
it('should update the apiConfig for an existing conversation when called with a valid conversationId and apiConfig', async () => { it('should update the apiConfig for an existing conversation when called with a valid conversationId and apiConfig', async () => {
await act(async () => { const { result } = renderHook(() => useConversation(), {
const { result, waitForNextUpdate } = renderHook(() => useConversation(), { wrapper: ({ children }: React.PropsWithChildren<{}>) => (
wrapper: ({ children }: React.PropsWithChildren<{}>) => ( <TestProviders providerContext={{ http: httpMock }}>{children}</TestProviders>
<TestProviders providerContext={{ http: httpMock }}>{children}</TestProviders> ),
), });
}); await waitFor(() => new Promise((resolve) => resolve(null)));
await waitForNextUpdate();
await act(async () => {
await result.current.setApiConfig({ await result.current.setApiConfig({
conversation: WELCOME_CONVERSATION, conversation: WELCOME_CONVERSATION,
apiConfig: mockConvo.apiConfig, apiConfig: mockConvo.apiConfig,
}); });
});
expect(createConversation).toHaveBeenCalledWith({ expect(createConversation).toHaveBeenCalledWith({
http: httpMock, http: httpMock,
conversation: { ...WELCOME_CONVERSATION, apiConfig: mockConvo.apiConfig, id: '' }, conversation: { ...WELCOME_CONVERSATION, apiConfig: mockConvo.apiConfig, id: '' },
});
}); });
}); });
it('should remove the last message from a conversation when called with valid conversationId', async () => { it('should remove the last message from a conversation when called with valid conversationId', async () => {
await act(async () => { const { result } = renderHook(() => useConversation(), {
const { result, waitForNextUpdate } = renderHook(() => useConversation(), { wrapper: ({ children }: React.PropsWithChildren<{}>) => (
wrapper: ({ children }: React.PropsWithChildren<{}>) => ( <TestProviders providerContext={{ http: httpMock }}>{children}</TestProviders>
<TestProviders providerContext={{ http: httpMock }}>{children}</TestProviders> ),
),
});
await waitForNextUpdate();
getConversationById.mockResolvedValue(mockConvo);
const removeResult = await result.current.removeLastMessage('new-convo');
expect(removeResult).toEqual([message]);
}); });
await waitFor(() => new Promise((resolve) => resolve(null)));
getConversationById.mockResolvedValue(mockConvo);
let removeResult;
await act(async () => {
removeResult = await result.current.removeLastMessage('new-convo');
});
expect(removeResult).toEqual([message]);
}); });
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { renderHook, act } from '@testing-library/react-hooks'; import { renderHook, act, waitFor } from '@testing-library/react';
import { useCurrentConversation, Props } from '.'; import { useCurrentConversation, Props } from '.';
import { useConversation } from '../use_conversation'; import { useConversation } from '../use_conversation';
import deepEqual from 'fast-deep-equal'; import deepEqual from 'fast-deep-equal';
@ -49,12 +49,15 @@ describe('useCurrentConversation', () => {
}; };
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks();
(useConversation as jest.Mock).mockReturnValue(mockUseConversation); (useConversation as jest.Mock).mockReturnValue(mockUseConversation);
(deepEqual as jest.Mock).mockReturnValue(false); (deepEqual as jest.Mock).mockReturnValue(false);
(find as jest.Mock).mockReturnValue(undefined); (find as jest.Mock).mockReturnValue(undefined);
}); });
afterEach(() => {
jest.clearAllMocks();
});
const defaultProps: Props = { const defaultProps: Props = {
// @ts-ignore not exact system prompt type, ok for test // @ts-ignore not exact system prompt type, ok for test
allSystemPrompts: [{ id: 'system-prompt-id' }, { id: 'something-crazy' }], allSystemPrompts: [{ id: 'system-prompt-id' }, { id: 'something-crazy' }],
@ -321,16 +324,19 @@ describe('useCurrentConversation', () => {
await act(async () => { await act(async () => {
await result.current.handleCreateConversation(); await result.current.handleCreateConversation();
}); });
const { defaultSystemPromptId: _, ...everythingExceptSystemPromptId } = const { defaultSystemPromptId: _, ...everythingExceptSystemPromptId } =
mockData.welcome_id.apiConfig; mockData.welcome_id.apiConfig;
expect(mockUseConversation.createConversation).toHaveBeenCalledWith({ await waitFor(() =>
apiConfig: { expect(mockUseConversation.createConversation).toHaveBeenCalledWith({
...everythingExceptSystemPromptId, apiConfig: {
defaultSystemPromptId: 'LBOi3JEBy3uD9EGi1d_G', ...everythingExceptSystemPromptId,
}, defaultSystemPromptId: 'LBOi3JEBy3uD9EGi1d_G',
title: 'New chat', },
}); title: 'New chat',
})
);
}); });
it('should delete a conversation', async () => { it('should delete a conversation', async () => {

View file

@ -207,6 +207,11 @@ export const useCurrentConversation = ({
// if no Welcome convo exists, create one // if no Welcome convo exists, create one
getDefaultConversation({ cTitle: WELCOME_CONVERSATION_TITLE }); getDefaultConversation({ cTitle: WELCOME_CONVERSATION_TITLE });
// on the off chance that the conversation is not found, return
if (!nextConversation) {
return;
}
if (nextConversation && nextConversation.id === '') { if (nextConversation && nextConversation.id === '') {
// This is a default conversation that has not yet been initialized // This is a default conversation that has not yet been initialized
const conversation = await initializeDefaultConversationWithConnector(nextConversation); const conversation = await initializeDefaultConversationWithConnector(nextConversation);

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { renderHook } from '@testing-library/react-hooks'; import { renderHook } from '@testing-library/react';
import { useAssistantContext } from '.'; import { useAssistantContext } from '.';
import useLocalStorage from 'react-use/lib/useLocalStorage'; import useLocalStorage from 'react-use/lib/useLocalStorage';
@ -18,10 +18,8 @@ describe('AssistantContext', () => {
beforeEach(() => jest.clearAllMocks()); beforeEach(() => jest.clearAllMocks());
test('it throws an error when useAssistantContext hook is used without a SecurityAssistantContext', () => { test('it throws an error when useAssistantContext hook is used without a SecurityAssistantContext', () => {
const { result } = renderHook(useAssistantContext); expect(() => renderHook(useAssistantContext)).toThrow(
/useAssistantContext must be used within a AssistantProvider/
expect(result.error).toEqual(
new Error('useAssistantContext must be used within a AssistantProvider')
); );
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { act, waitFor, renderHook } from '@testing-library/react';
import { useLoadActionTypes, Props } from '.'; import { useLoadActionTypes, Props } from '.';
import { mockActionTypes } from '../../mock/connectors'; import { mockActionTypes } from '../../mock/connectors';
@ -32,10 +32,8 @@ describe('useLoadActionTypes', () => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
it('should call api to load action types', async () => { it('should call api to load action types', async () => {
await act(async () => { renderHook(() => useLoadActionTypes(defaultProps));
const { waitForNextUpdate } = renderHook(() => useLoadActionTypes(defaultProps)); await waitFor(() => {
await waitForNextUpdate();
expect(defaultProps.http.get).toHaveBeenCalledWith('/api/actions/connector_types', { expect(defaultProps.http.get).toHaveBeenCalledWith('/api/actions/connector_types', {
query: { feature_id: 'generativeAIForSecurity' }, query: { feature_id: 'generativeAIForSecurity' },
}); });
@ -44,26 +42,20 @@ describe('useLoadActionTypes', () => {
}); });
it('should return sorted action types', async () => { it('should return sorted action types', async () => {
await act(async () => { const { result } = renderHook(() => useLoadActionTypes(defaultProps));
const { result, waitForNextUpdate } = renderHook(() => useLoadActionTypes(defaultProps)); await waitFor(() =>
await waitForNextUpdate(); expect(result.current).resolves.toStrictEqual(
await expect(result.current).resolves.toStrictEqual(
mockActionTypes.sort((a, b) => a.name.localeCompare(b.name)) mockActionTypes.sort((a, b) => a.name.localeCompare(b.name))
); )
}); );
}); });
it('should display error toast when api throws error', async () => { it('should display error toast when api throws error', async () => {
await act(async () => { await act(async () => {
const mockHttp = { const mockHttp = {
get: jest.fn().mockRejectedValue(new Error('this is an error')), get: jest.fn().mockRejectedValue(new Error('this is an error')),
} as unknown as Props['http']; } as unknown as Props['http'];
const { waitForNextUpdate } = renderHook(() => renderHook(() => useLoadActionTypes({ ...defaultProps, http: mockHttp }));
useLoadActionTypes({ ...defaultProps, http: mockHttp }) await waitFor(() => expect(toasts.addError).toHaveBeenCalled());
);
await waitForNextUpdate();
expect(toasts.addError).toHaveBeenCalled();
}); });
}); });
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook } from '@testing-library/react';
import { useLoadConnectors, Props } from '.'; import { useLoadConnectors, Props } from '.';
import { mockConnectors } from '../../mock/connectors'; import { mockConnectors } from '../../mock/connectors';
@ -68,37 +68,27 @@ describe('useLoadConnectors', () => {
jest.clearAllMocks(); jest.clearAllMocks();
}); });
it('should call api to load action types', async () => { it('should call api to load action types', async () => {
await act(async () => { renderHook(() => useLoadConnectors(defaultProps));
const { waitForNextUpdate } = renderHook(() => useLoadConnectors(defaultProps)); await waitFor(() => {
await waitForNextUpdate();
expect(defaultProps.http.get).toHaveBeenCalledWith('/api/actions/connectors'); expect(defaultProps.http.get).toHaveBeenCalledWith('/api/actions/connectors');
expect(toasts.addError).not.toHaveBeenCalled(); expect(toasts.addError).not.toHaveBeenCalled();
}); });
}); });
it('should return sorted action types, removing isMissingSecrets and wrong action type ids', async () => { it('should return sorted action types, removing isMissingSecrets and wrong action type ids', async () => {
await act(async () => { const { result } = renderHook(() => useLoadConnectors(defaultProps));
const { result, waitForNextUpdate } = renderHook(() => useLoadConnectors(defaultProps)); await waitFor(() => {
await waitForNextUpdate(); expect(result.current).resolves.toStrictEqual(
await expect(result.current).resolves.toStrictEqual(
// @ts-ignore ts does not like config, but we define it in the mock data // @ts-ignore ts does not like config, but we define it in the mock data
loadConnectorsResult.map((c) => ({ ...c, apiProvider: c.config.apiProvider })) loadConnectorsResult.map((c) => ({ ...c, apiProvider: c.config.apiProvider }))
); );
}); });
}); });
it('should display error toast when api throws error', async () => { it('should display error toast when api throws error', async () => {
await act(async () => { const mockHttp = {
const mockHttp = { get: jest.fn().mockRejectedValue(new Error('this is an error')),
get: jest.fn().mockRejectedValue(new Error('this is an error')), } as unknown as Props['http'];
} as unknown as Props['http']; renderHook(() => useLoadConnectors({ ...defaultProps, http: mockHttp }));
const { waitForNextUpdate } = renderHook(() => await waitFor(() => expect(toasts.addError).toHaveBeenCalled());
useLoadConnectors({ ...defaultProps, http: mockHttp })
);
await waitForNextUpdate();
expect(toasts.addError).toHaveBeenCalled();
});
}); });
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook } from '@testing-library/react';
import { useStream } from './use_stream'; import { useStream } from './use_stream';
const refetchCurrentConversation = jest.fn(); const refetchCurrentConversation = jest.fn();
@ -49,7 +49,7 @@ describe.skip('useStream', () => {
}); });
it('Should stream response. isLoading/isStreaming are true while streaming, isLoading/isStreaming are false when streaming completes', async () => { it('Should stream response. isLoading/isStreaming are true while streaming, isLoading/isStreaming are false when streaming completes', async () => {
const { result, waitFor } = renderHook(() => useStream(defaultProps)); const { result } = renderHook(() => useStream(defaultProps));
expect(reader).toHaveBeenCalledTimes(1); expect(reader).toHaveBeenCalledTimes(1);
await waitFor(() => { await waitFor(() => {
expect(result.current).toEqual({ expect(result.current).toEqual({
@ -107,7 +107,7 @@ describe.skip('useStream', () => {
releaseLock: jest.fn(), releaseLock: jest.fn(),
closed: jest.fn().mockResolvedValue(true), closed: jest.fn().mockResolvedValue(true),
} as unknown as ReadableStreamDefaultReader<Uint8Array>; } as unknown as ReadableStreamDefaultReader<Uint8Array>;
const { result, waitForNextUpdate } = renderHook(() => const { result } = renderHook(() =>
useStream({ useStream({
...defaultProps, ...defaultProps,
reader: errorReader, reader: errorReader,
@ -115,7 +115,7 @@ describe.skip('useStream', () => {
); );
expect(result.current.error).toBeUndefined(); expect(result.current.error).toBeUndefined();
await waitForNextUpdate(); await waitFor(() => new Promise((resolve) => resolve(null)));
expect(result.current.error).toBe(errorMessage); expect(result.current.error).toBe(errorMessage);
expect(result.current.isLoading).toBe(false); expect(result.current.isLoading).toBe(false);

View file

@ -22,7 +22,14 @@ jest.mock('@kbn/elastic-assistant', () => ({
jest.mock('../common/hooks/use_experimental_features'); jest.mock('../common/hooks/use_experimental_features');
describe('AssistantOverlay', () => { describe('AssistantOverlay', () => {
const queryClient = new QueryClient(); const queryClient = new QueryClient({
defaultOptions: {
queries: {
cacheTime: Infinity,
retry: false,
},
},
});
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { waitFor, renderHook } from '@testing-library/react';
import { httpServiceMock, type HttpSetupMock } from '@kbn/core-http-browser-mocks'; import { httpServiceMock, type HttpSetupMock } from '@kbn/core-http-browser-mocks';
import type { Storage } from '@kbn/kibana-utils-plugin/public'; import type { Storage } from '@kbn/kibana-utils-plugin/public';
import { createConversations } from './provider'; import { createConversations } from './provider';
@ -166,47 +166,43 @@ describe('createConversations', () => {
}); });
it('should call bulk conversations with the transformed conversations from the local storage', async () => { it('should call bulk conversations with the transformed conversations from the local storage', async () => {
await act(async () => { renderHook(() =>
const { waitForNextUpdate } = renderHook(() => createConversations(
createConversations( coreMock.createStart().notifications,
coreMock.createStart().notifications, http,
http, mockStorage as unknown as Storage
mockStorage as unknown as Storage )
) );
); await waitFor(() => new Promise((resolve) => resolve(null)));
await waitForNextUpdate(); expect(http.fetch.mock.calls[0][0]).toBe(
expect(http.fetch.mock.calls[0][0]).toBe( '/internal/elastic_assistant/current_user/conversations/_bulk_action'
'/internal/elastic_assistant/current_user/conversations/_bulk_action' );
); expect(
expect( http.fetch.mock.calls[0].length > 1
http.fetch.mock.calls[0].length > 1 ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
? // eslint-disable-next-line @typescript-eslint/no-explicit-any JSON.parse((http.fetch.mock.calls[0] as any[])[1]?.body).create.length
JSON.parse((http.fetch.mock.calls[0] as any[])[1]?.body).create.length : 0
: 0 ).toBe(2);
).toBe(2);
});
}); });
it('should add missing actionTypeId to apiConfig', async () => { it('should add missing actionTypeId to apiConfig', async () => {
await act(async () => { renderHook(() =>
const { waitForNextUpdate } = renderHook(() => createConversations(
createConversations( coreMock.createStart().notifications,
coreMock.createStart().notifications, http,
http, mockStorage as unknown as Storage
mockStorage as unknown as Storage )
) );
); await waitFor(() => new Promise((resolve) => resolve(null)));
await waitForNextUpdate(); expect(http.fetch.mock.calls[0][0]).toBe(
expect(http.fetch.mock.calls[0][0]).toBe( '/internal/elastic_assistant/current_user/conversations/_bulk_action'
'/internal/elastic_assistant/current_user/conversations/_bulk_action' );
); const createdConversations =
const createdConversations = http.fetch.mock.calls[0].length > 1
http.fetch.mock.calls[0].length > 1 ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
? // eslint-disable-next-line @typescript-eslint/no-explicit-any JSON.parse((http.fetch.mock.calls[0] as any[])[1]?.body)?.create
JSON.parse((http.fetch.mock.calls[0] as any[])[1]?.body)?.create : [];
: []; expect(createdConversations[0].apiConfig.actionTypeId).toEqual('.bedrock');
expect(createdConversations[0].apiConfig.actionTypeId).toEqual('.bedrock'); expect(createdConversations[1].apiConfig.actionTypeId).toEqual('.gen-ai');
expect(createdConversations[1].apiConfig.actionTypeId).toEqual('.gen-ai');
});
}); });
}); });

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { renderHook } from '@testing-library/react-hooks'; import { renderHook } from '@testing-library/react';
import { useAssistantTelemetry } from '.'; import { useAssistantTelemetry } from '.';
import { BASE_SECURITY_CONVERSATIONS } from '../content/conversations'; import { BASE_SECURITY_CONVERSATIONS } from '../content/conversations';
import { createTelemetryServiceMock } from '../../common/lib/telemetry/telemetry_service.mock'; import { createTelemetryServiceMock } from '../../common/lib/telemetry/telemetry_service.mock';

View file

@ -4,7 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License
* 2.0. * 2.0.
*/ */
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useBaseConversations } from '.'; import { useBaseConversations } from '.';
import { useLinkAuthorized } from '../../common/links'; import { useLinkAuthorized } from '../../common/links';
import { useKibana as mockUseKibana } from '../../common/lib/kibana/__mocks__'; import { useKibana as mockUseKibana } from '../../common/lib/kibana/__mocks__';

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { renderHook, act } from '@testing-library/react';
import { useAddToNewCase } from '.'; import { useAddToNewCase } from '.';
import { TestProviders } from '../../../../../../common/mock'; import { TestProviders } from '../../../../../../common/mock';

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { act, renderHook } from '@testing-library/react-hooks'; import { renderHook, act } from '@testing-library/react';
import { useAddToExistingCase } from '.'; import { useAddToExistingCase } from '.';
import { useKibana } from '../../../../../../common/lib/kibana'; import { useKibana } from '../../../../../../common/lib/kibana';

View file

@ -5,7 +5,7 @@
* 2.0. * 2.0.
*/ */
import { renderHook } from '@testing-library/react-hooks'; import { renderHook } from '@testing-library/react';
import { useAssistantOverlay } from '@kbn/elastic-assistant'; import { useAssistantOverlay } from '@kbn/elastic-assistant';
import { useAssistantAvailability } from '../../../../../assistant/use_assistant_availability'; import { useAssistantAvailability } from '../../../../../assistant/use_assistant_availability';

View file

@ -7,7 +7,7 @@
import { useLoadConnectors } from '@kbn/elastic-assistant'; import { useLoadConnectors } from '@kbn/elastic-assistant';
import { useFetchAnonymizationFields } from '@kbn/elastic-assistant/impl/assistant/api/anonymization_fields/use_fetch_anonymization_fields'; import { useFetchAnonymizationFields } from '@kbn/elastic-assistant/impl/assistant/api/anonymization_fields/use_fetch_anonymization_fields';
import { renderHook, act } from '@testing-library/react-hooks'; import { renderHook, act } from '@testing-library/react';
import React from 'react'; import React from 'react';
import { useKibana } from '../../../common/lib/kibana'; import { useKibana } from '../../../common/lib/kibana';

View file

@ -7,7 +7,7 @@
import type { HttpSetupMock } from '@kbn/core-http-browser-mocks'; import type { HttpSetupMock } from '@kbn/core-http-browser-mocks';
import { coreMock } from '@kbn/core/public/mocks'; import { coreMock } from '@kbn/core/public/mocks';
import { act, renderHook } from '@testing-library/react-hooks'; import { renderHook, act } from '@testing-library/react';
import { attackDiscoveryStatus, usePollApi } from './use_poll_api'; import { attackDiscoveryStatus, usePollApi } from './use_poll_api';
import moment from 'moment/moment'; import moment from 'moment/moment';
import { kibanaMock } from '../../../../common/mock'; import { kibanaMock } from '../../../../common/mock';