Skip to content

Commit

Permalink
[React18] Migrate test suites to account for testing library upgrades…
Browse files Browse the repository at this point in the history
… security-generative-ai (elastic#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 <[email protected]>
  • Loading branch information
eokoneyo and elasticmachine authored Dec 12, 2024
1 parent 0f160ab commit 6ece92e
Show file tree
Hide file tree
Showing 35 changed files with 390 additions and 409 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 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 type { ReactNode } from 'react';
Expand Down Expand Up @@ -41,9 +41,7 @@ describe('useFetchAnonymizationFields', () => {
wrapper: createWrapper(),
});

await act(async () => {
const { waitForNextUpdate } = renderHook(() => useFetchAnonymizationFields());
await waitForNextUpdate();
await waitFor(() => {
expect(http.fetch).toHaveBeenCalledWith(
'/api/security_ai_assistant/anonymization_fields/_find',
{
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 { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ReactNode } from 'react';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

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

import {
DeleteConversationParams,
Expand All @@ -32,18 +32,18 @@ describe('conversations api', () => {
await act(async () => {
const deleteProps = { http, toasts, id: 'test' } as unknown as DeleteConversationParams;

const { waitForNextUpdate } = renderHook(() => deleteConversation(deleteProps));
await waitForNextUpdate();

expect(deleteProps.http.fetch).toHaveBeenCalledWith(
'/api/security_ai_assistant/current_user/conversations/test',
{
method: 'DELETE',
signal: undefined,
version: '2023-10-31',
}
);
expect(toasts.addError).not.toHaveBeenCalled();
renderHook(() => deleteConversation(deleteProps));
await waitFor(() => {
expect(deleteProps.http.fetch).toHaveBeenCalledWith(
'/api/security_ai_assistant/current_user/conversations/test',
{
method: 'DELETE',
signal: undefined,
version: '2023-10-31',
}
);
expect(toasts.addError).not.toHaveBeenCalled();
});
});
});

Expand All @@ -58,18 +58,18 @@ describe('conversations api', () => {
it('should call api to get conversation', async () => {
await act(async () => {
const getProps = { http, toasts, id: 'test' } as unknown as GetConversationByIdParams;
const { waitForNextUpdate } = renderHook(() => getConversationById(getProps));
await waitForNextUpdate();

expect(getProps.http.fetch).toHaveBeenCalledWith(
'/api/security_ai_assistant/current_user/conversations/test',
{
method: 'GET',
signal: undefined,
version: '2023-10-31',
}
);
expect(toasts.addError).not.toHaveBeenCalled();
renderHook(() => getConversationById(getProps));
await waitFor(() => {
expect(getProps.http.fetch).toHaveBeenCalledWith(
'/api/security_ai_assistant/current_user/conversations/test',
{
method: 'GET',
signal: undefined,
version: '2023-10-31',
}
);
expect(toasts.addError).not.toHaveBeenCalled();
});
});
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 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 type { ReactNode } from 'react';
Expand Down Expand Up @@ -41,11 +41,7 @@ describe('useFetchCurrentUserConversations', () => {
wrapper: createWrapper(),
});

await act(async () => {
const { waitForNextUpdate } = renderHook(() =>
useFetchCurrentUserConversations(defaultProps)
);
await waitForNextUpdate();
await waitFor(() => {
expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/api/security_ai_assistant/current_user/conversations/_find',
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 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 { postEvaluation as _postEvaluation } from './evaluate';
import { useMutation as _useMutation } from '@tanstack/react-query';
Expand Down Expand Up @@ -50,10 +50,8 @@ describe('usePerformEvaluation', () => {
jest.clearAllMocks();
});
it('should call api with undefined evalParams', async () => {
await act(async () => {
const { waitForNextUpdate } = renderHook(() => usePerformEvaluation(defaultProps));
await waitForNextUpdate();

renderHook(() => usePerformEvaluation(defaultProps));
await waitFor(() => {
expect(defaultProps.http.post).toHaveBeenCalledWith('/internal/elastic_assistant/evaluate', {
body: undefined,
headers: {
Expand All @@ -80,37 +78,29 @@ describe('usePerformEvaluation', () => {
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', {
body: '{"graphs":["d","c"],"datasetName":"kewl","connectorIds":["h","g"],"runName":"test run"}',
headers: {
'Content-Type': 'application/json',
},
signal: undefined,
version: API_VERSIONS.internal.v1,
});
});
})
);
});

it('should return evaluation response', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook(() => usePerformEvaluation(defaultProps));
await waitForNextUpdate();

await expect(result.current).resolves.toStrictEqual(statusResponse);
});
const { result } = renderHook(() => usePerformEvaluation(defaultProps));
await waitFor(() => expect(result.current).resolves.toStrictEqual(statusResponse));
});

it('should display error toast when api throws error', async () => {
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());
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { act, renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import {
useKnowledgeBaseIndices,
UseKnowledgeBaseIndicesParams,
Expand Down Expand Up @@ -48,10 +48,8 @@ describe('useKnowledgeBaseIndices', () => {
});

it('should call api to get knowledge base indices', async () => {
await act(async () => {
const { waitForNextUpdate } = renderHook(() => useKnowledgeBaseIndices(defaultProps));
await waitForNextUpdate();

renderHook(() => useKnowledgeBaseIndices(defaultProps));
await waitFor(() => {
expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/knowledge_base/_indices',
{
Expand All @@ -65,20 +63,17 @@ describe('useKnowledgeBaseIndices', () => {
});

it('should return indices response', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook(() => useKnowledgeBaseIndices(defaultProps));
await waitForNextUpdate();

await expect(result.current).resolves.toStrictEqual(indicesResponse);
const { result } = renderHook(() => useKnowledgeBaseIndices(defaultProps));
await waitFor(() => {
expect(result.current).resolves.toStrictEqual(indicesResponse);
});
});

it('should display error toast when api throws error', async () => {
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();
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 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 { getKnowledgeBaseStatus as _getKnowledgeBaseStatus } from './api';

Expand Down Expand Up @@ -49,10 +49,8 @@ describe('useKnowledgeBaseStatus', () => {
jest.clearAllMocks();
});
it('should call api to get knowledge base status without resource arg', async () => {
await act(async () => {
const { waitForNextUpdate } = renderHook(() => useKnowledgeBaseStatus(defaultProps));
await waitForNextUpdate();

renderHook(() => useKnowledgeBaseStatus(defaultProps));
await waitFor(() => {
expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/knowledge_base/',
{
Expand All @@ -65,39 +63,27 @@ describe('useKnowledgeBaseStatus', () => {
});
});
it('should call api to get knowledge base status with resource arg', async () => {
await act(async () => {
const { waitForNextUpdate } = renderHook(() =>
useKnowledgeBaseStatus({ ...defaultProps, resource: 'something' })
);
await waitForNextUpdate();

renderHook(() => useKnowledgeBaseStatus({ ...defaultProps, resource: 'something' }));
await waitFor(() =>
expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/knowledge_base/something',
{
method: 'GET',
signal: undefined,
version: '1',
}
);
});
)
);
});

it('should return status response', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook(() => useKnowledgeBaseStatus(defaultProps));
await waitForNextUpdate();

await expect(result.current).resolves.toStrictEqual(statusResponse);
});
const { result } = renderHook(() => useKnowledgeBaseStatus(defaultProps));
await waitFor(() => expect(result.current).resolves.toStrictEqual(statusResponse));
});

it('should display error toast when api throws error', async () => {
getKnowledgeBaseStatusMock.mockRejectedValue(new Error('this is an error'));
await act(async () => {
const { waitForNextUpdate } = renderHook(() => useKnowledgeBaseStatus(defaultProps));
await waitForNextUpdate();

expect(toasts.addError).toHaveBeenCalled();
});
renderHook(() => useKnowledgeBaseStatus(defaultProps));
await waitFor(() => expect(toasts.addError).toHaveBeenCalled());
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 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 { postKnowledgeBase as _postKnowledgeBase } from './api';
import { useMutation as _useMutation } from '@tanstack/react-query';
Expand Down Expand Up @@ -50,10 +50,8 @@ describe('useSetupKnowledgeBase', () => {
jest.clearAllMocks();
});
it('should call api to post knowledge base setup', async () => {
await act(async () => {
const { waitForNextUpdate } = renderHook(() => useSetupKnowledgeBase(defaultProps));
await waitForNextUpdate();

renderHook(() => useSetupKnowledgeBase(defaultProps));
await waitFor(() => {
expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/knowledge_base/',
{
Expand All @@ -73,36 +71,27 @@ describe('useSetupKnowledgeBase', () => {
opts.onError(e);
}
});
await act(async () => {
const { waitForNextUpdate } = renderHook(() => useSetupKnowledgeBase(defaultProps));
await waitForNextUpdate();

renderHook(() => useSetupKnowledgeBase(defaultProps));
await waitFor(() =>
expect(defaultProps.http.fetch).toHaveBeenCalledWith(
'/internal/elastic_assistant/knowledge_base/something',
{
method: 'POST',
version: '1',
}
);
});
)
);
});

it('should return setup response', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook(() => useSetupKnowledgeBase(defaultProps));
await waitForNextUpdate();

await expect(result.current).resolves.toStrictEqual(statusResponse);
});
const { result } = renderHook(() => useSetupKnowledgeBase(defaultProps));
await waitFor(() => expect(result.current).resolves.toStrictEqual(statusResponse));
});

it('should display error toast when api throws error', async () => {
postKnowledgeBaseMock.mockRejectedValue(new Error('this is an error'));
await act(async () => {
const { waitForNextUpdate } = renderHook(() => useSetupKnowledgeBase(defaultProps));
await waitForNextUpdate();

expect(toasts.addError).toHaveBeenCalled();
});
renderHook(() => useSetupKnowledgeBase(defaultProps));
await waitFor(() => expect(toasts.addError).toHaveBeenCalled());
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 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 type { ReactNode } from 'react';
Expand Down Expand Up @@ -41,9 +41,7 @@ describe('useFetchPrompts', () => {
wrapper: createWrapper(),
});

await act(async () => {
const { waitForNextUpdate } = renderHook(() => useFetchPrompts());
await waitForNextUpdate();
await waitFor(() => {
expect(http.fetch).toHaveBeenCalledWith('/api/security_ai_assistant/prompts/_find', {
method: 'GET',
query: {
Expand Down
Loading

0 comments on commit 6ece92e

Please sign in to comment.