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 security-generative-ai (#201160) (#203960)

# Backport

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

<!--- 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-12T05:21:20Z","message":"[React18]
Migrate test suites to account for testing library upgrades
security-generative-ai (#201160)\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":"6ece92e9e121d6c90950ff7d2f2f5195aafdbfb9","branchLabelMapping":{"^v9.0.0$":"main","^v8.18.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","backport:prev-minor","Team:Security
Generative AI","React@18"],"title":"[React18] Migrate test suites to
account for testing library upgrades
security-generative-ai","number":201160,"url":"https://github.com/elastic/kibana/pull/201160","mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
security-generative-ai (#201160)\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":"6ece92e9e121d6c90950ff7d2f2f5195aafdbfb9"}},"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/201160","number":201160,"mergeCommit":{"message":"[React18]
Migrate test suites to account for testing library upgrades
security-generative-ai (#201160)\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":"6ece92e9e121d6c90950ff7d2f2f5195aafdbfb9"}}]}]
BACKPORT-->

Co-authored-by: Eyo O. Eyo <[email protected]>
Co-authored-by: Elastic Machine <[email protected]>
  • Loading branch information
3 people authored Dec 13, 2024
1 parent 36c1cd6 commit 4b0adec
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 4b0adec

Please sign in to comment.