[React18] Migrate test suites to account for testing library upgrades response-ops (#201141)

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.
This commit is contained in:
Eyo O. Eyo 2024-11-22 17:43:23 +01:00 committed by GitHub
parent ec7e1a808f
commit 3890bde1ab
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
149 changed files with 1531 additions and 1774 deletions

View file

@ -8,7 +8,7 @@
*/
import type { ControlGroupRuntimeState } from '@kbn/controls-plugin/public';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, act, renderHook } from '@testing-library/react';
import { useControlGroupSyncToLocalStorage } from './use_control_group_sync_to_local_storage';
import { Storage } from '@kbn/kibana-utils-plugin/public';
@ -34,77 +34,97 @@ describe('Filters Sync to Local Storage', () => {
writable: true,
});
});
afterEach(() => {
mockLocalStorage = {};
});
it('should not be undefined if localStorage has initial value', () => {
it('should not be undefined if localStorage has initial value', async () => {
global.localStorage.setItem(TEST_STORAGE_KEY, JSON.stringify(DEFAULT_STORED_VALUE));
const { result, waitForNextUpdate } = renderHook(() =>
const { result } = renderHook(() =>
useControlGroupSyncToLocalStorage({
Storage,
storageKey: TEST_STORAGE_KEY,
shouldSync: true,
})
);
waitForNextUpdate();
expect(result.current.controlGroupState).toMatchObject(DEFAULT_STORED_VALUE);
await waitFor(() =>
expect(result.current.controlGroupState).toMatchObject(DEFAULT_STORED_VALUE)
);
});
it('should be undefined if localstorage as NO initial value', () => {
const { result, waitForNextUpdate } = renderHook(() =>
it('should be undefined if localstorage as NO initial value', async () => {
const { result } = renderHook(() =>
useControlGroupSyncToLocalStorage({
Storage,
storageKey: TEST_STORAGE_KEY,
shouldSync: true,
})
);
waitForNextUpdate();
expect(result.current.controlGroupState).toBeUndefined();
expect(result.current.setControlGroupState).toBeTruthy();
await waitFor(() =>
expect(result.current).toEqual(
expect.objectContaining({
controlGroupState: undefined,
setControlGroupState: expect.any(Function),
})
)
);
});
it('should be update values to local storage when sync is ON', () => {
const { result, waitFor } = renderHook(() =>
it('should be update values to local storage when sync is ON', async () => {
const { result } = renderHook(() =>
useControlGroupSyncToLocalStorage({
Storage,
storageKey: TEST_STORAGE_KEY,
shouldSync: true,
})
);
waitFor(() => {
await waitFor(() => {
expect(result.current.controlGroupState).toBeUndefined();
expect(result.current.setControlGroupState).toBeTruthy();
});
result.current.setControlGroupState(DEFAULT_STORED_VALUE);
waitFor(() => {
act(() => {
result.current.setControlGroupState(DEFAULT_STORED_VALUE);
});
await waitFor(() => {
expect(result.current.controlGroupState).toMatchObject(DEFAULT_STORED_VALUE);
expect(global.localStorage.getItem(TEST_STORAGE_KEY)).toBe(
JSON.stringify(DEFAULT_STORED_VALUE)
);
});
});
it('should not update values to local storage when sync is OFF', () => {
const { waitFor, result, rerender } = renderHook(() =>
useControlGroupSyncToLocalStorage({
Storage,
storageKey: TEST_STORAGE_KEY,
shouldSync: true,
})
);
it('should not update values to local storage when sync is OFF', async () => {
const initialProps = {
Storage,
storageKey: TEST_STORAGE_KEY,
shouldSync: true,
};
const { result, rerender } = renderHook(useControlGroupSyncToLocalStorage, {
initialProps,
});
// Sync is ON
waitFor(() => {
await waitFor(() => {
expect(result.current.controlGroupState).toBeUndefined();
expect(result.current.setControlGroupState).toBeTruthy();
});
result.current.setControlGroupState(DEFAULT_STORED_VALUE);
waitFor(() => {
act(() => {
result.current.setControlGroupState(DEFAULT_STORED_VALUE);
});
await waitFor(() => {
expect(result.current.controlGroupState).toMatchObject(DEFAULT_STORED_VALUE);
});
// Sync is OFF
rerender({ storageKey: TEST_STORAGE_KEY, shouldSync: false });
result.current.setControlGroupState(ANOTHER_SAMPLE_VALUE);
waitFor(() => {
rerender({ ...initialProps, shouldSync: false });
act(() => {
result.current.setControlGroupState(ANOTHER_SAMPLE_VALUE);
});
await waitFor(() => {
expect(result.current.controlGroupState).toMatchObject(ANOTHER_SAMPLE_VALUE);
// old value
expect(global.localStorage.getItem(TEST_STORAGE_KEY)).toBe(

View file

@ -10,7 +10,7 @@
import React from 'react';
import { AlertConsumers } from '@kbn/rule-data-utils';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import { renderHook, waitFor } from '@testing-library/react';
import { DataView } from '@kbn/data-views-plugin/common';
import { httpServiceMock } from '@kbn/core-http-browser-mocks';
import { notificationServiceMock } from '@kbn/core-notifications-browser-mocks';
@ -69,7 +69,7 @@ describe('useAlertsDataView', () => {
dataView: undefined,
};
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useAlertsDataView({
...mockServices,
@ -84,7 +84,7 @@ describe('useAlertsDataView', () => {
});
it('fetches indexes and fields for non-siem feature ids, returning a DataViewBase object', async () => {
const { result, waitForValueToChange } = renderHook(
const { result } = renderHook(
() =>
useAlertsDataView({
...mockServices,
@ -95,7 +95,7 @@ describe('useAlertsDataView', () => {
}
);
await waitForValueToChange(() => result.current.isLoading, { timeout: 5000 });
await waitFor(() => result.current.isLoading, { timeout: 5000 });
expect(mockFetchAlertsFields).toHaveBeenCalledTimes(1);
expect(mockFetchAlertsIndexNames).toHaveBeenCalledTimes(1);
@ -103,7 +103,7 @@ describe('useAlertsDataView', () => {
});
it('only fetches index names for the siem feature id, returning a DataView', async () => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useAlertsDataView({ ...mockServices, featureIds: [AlertConsumers.SIEM] }),
{
wrapper,
@ -117,7 +117,7 @@ describe('useAlertsDataView', () => {
});
it('does not fetch anything if siem and other feature ids are mixed together', async () => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useAlertsDataView({
...mockServices,
@ -141,7 +141,7 @@ describe('useAlertsDataView', () => {
it('returns an undefined data view if any of the queries fails', async () => {
mockFetchAlertsIndexNames.mockRejectedValue('error');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useAlertsDataView({ ...mockServices, featureIds: observabilityFeatureIds }),
{
wrapper,
@ -159,12 +159,9 @@ describe('useAlertsDataView', () => {
it('shows an error toast if any of the queries fails', async () => {
mockFetchAlertsIndexNames.mockRejectedValue('error');
const { waitFor } = renderHook(
() => useAlertsDataView({ ...mockServices, featureIds: observabilityFeatureIds }),
{
wrapper,
}
);
renderHook(() => useAlertsDataView({ ...mockServices, featureIds: observabilityFeatureIds }), {
wrapper,
});
await waitFor(() => expect(mockServices.toasts.addDanger).toHaveBeenCalled());
});

View file

@ -9,8 +9,7 @@
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import type { HttpStart } from '@kbn/core-http-browser';
import { useCreateRule } from './use_create_rule';

View file

@ -10,7 +10,7 @@
import React, { FC } from 'react';
import { AlertConsumers } from '@kbn/rule-data-utils';
import * as ReactQuery from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { testQueryClientConfig } from '../test_utils/test_query_client_config';
import { useFetchAlertsFieldsQuery } from './use_fetch_alerts_fields_query';
import { httpServiceMock } from '@kbn/core-http-browser-mocks';
@ -88,35 +88,37 @@ describe('useFetchAlertsFieldsQuery', () => {
});
it('should call the api only once', async () => {
const { result, rerender, waitForValueToChange } = renderHook(
const { result, rerender } = renderHook(
() => useFetchAlertsFieldsQuery({ http: mockHttpClient, featureIds: ['apm'] }),
{
wrapper,
}
);
await waitForValueToChange(() => result.current.data);
expect(mockHttpGet).toHaveBeenCalledTimes(1);
expect(result.current.data).toEqual({
browserFields: { fakeCategory: {} },
fields: [
{
name: 'fakeCategory',
},
],
await waitFor(() => {
expect(mockHttpGet).toHaveBeenCalledTimes(1);
expect(result.current.data).toEqual({
browserFields: { fakeCategory: {} },
fields: [
{
name: 'fakeCategory',
},
],
});
});
rerender();
expect(mockHttpGet).toHaveBeenCalledTimes(1);
expect(result.current.data).toEqual({
browserFields: { fakeCategory: {} },
fields: [
{
name: 'fakeCategory',
},
],
await waitFor(() => {
expect(mockHttpGet).toHaveBeenCalledTimes(1);
expect(result.current.data).toEqual({
browserFields: { fakeCategory: {} },
fields: [
{
name: 'fakeCategory',
},
],
});
});
});
@ -132,8 +134,10 @@ describe('useFetchAlertsFieldsQuery', () => {
}
);
expect(mockHttpGet).toHaveBeenCalledTimes(0);
expect(result.current.data).toEqual(emptyData);
await waitFor(() => {
expect(mockHttpGet).toHaveBeenCalledTimes(0);
expect(result.current.data).toEqual(emptyData);
});
});
it('should not fetch if all featureId are not valid', async () => {
@ -148,8 +152,10 @@ describe('useFetchAlertsFieldsQuery', () => {
}
);
expect(mockHttpGet).toHaveBeenCalledTimes(0);
expect(result.current.data).toEqual(emptyData);
await waitFor(() => {
expect(mockHttpGet).toHaveBeenCalledTimes(0);
expect(result.current.data).toEqual(emptyData);
});
});
it('should filter out the non valid feature id', async () => {
@ -164,9 +170,11 @@ describe('useFetchAlertsFieldsQuery', () => {
}
);
expect(mockHttpGet).toHaveBeenCalledTimes(1);
expect(mockHttpGet).toHaveBeenCalledWith('/internal/rac/alerts/browser_fields', {
query: { featureIds: ['apm', 'logs'] },
await waitFor(() => {
expect(mockHttpGet).toHaveBeenCalledTimes(1);
expect(mockHttpGet).toHaveBeenCalledWith('/internal/rac/alerts/browser_fields', {
query: { featureIds: ['apm', 'logs'] },
});
});
});
});

View file

@ -9,7 +9,7 @@
import React, { FunctionComponent } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { testQueryClientConfig } from '../test_utils/test_query_client_config';
import { useFetchAlertsIndexNamesQuery } from './use_fetch_alerts_index_names_query';
import { fetchAlertsIndexNames } from '../apis/fetch_alerts_index_names';
@ -56,14 +56,14 @@ describe('useFetchAlertsIndexNamesQuery', () => {
});
it('correctly caches the index names', async () => {
const { result, rerender, waitForValueToChange } = renderHook(
const { result, rerender } = renderHook(
() => useFetchAlertsIndexNamesQuery({ http: mockHttpClient, featureIds: ['apm'] }),
{
wrapper,
}
);
await waitForValueToChange(() => result.current.data);
await waitFor(() => result.current.data);
expect(mockFetchAlertsIndexNames).toHaveBeenCalledTimes(1);

View file

@ -9,7 +9,7 @@
import React, { FunctionComponent } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook, waitFor } from '@testing-library/react';
import { testQueryClientConfig } from '../test_utils/test_query_client_config';
import { useFetchFlappingSettings } from './use_fetch_flapping_settings';
import { httpServiceMock } from '@kbn/core-http-browser-mocks';
@ -43,12 +43,9 @@ describe('useFetchFlappingSettings', () => {
});
test('should call fetchFlappingSettings with the correct parameters', async () => {
const { result, waitFor } = renderHook(
() => useFetchFlappingSettings({ http, enabled: true }),
{
wrapper,
}
);
const { result } = renderHook(() => useFetchFlappingSettings({ http, enabled: true }), {
wrapper,
});
await waitFor(() => {
return expect(result.current.isInitialLoading).toEqual(false);
@ -66,12 +63,9 @@ describe('useFetchFlappingSettings', () => {
});
test('should not call fetchFlappingSettings if enabled is false', async () => {
const { result, waitFor } = renderHook(
() => useFetchFlappingSettings({ http, enabled: false }),
{
wrapper,
}
);
const { result } = renderHook(() => useFetchFlappingSettings({ http, enabled: false }), {
wrapper,
});
await waitFor(() => {
return expect(result.current.isInitialLoading).toEqual(false);
@ -82,7 +76,7 @@ describe('useFetchFlappingSettings', () => {
test('should call onSuccess when the fetching was successful', async () => {
const onSuccessMock = jest.fn();
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useFetchFlappingSettings({ http, enabled: true, onSuccess: onSuccessMock }),
{
wrapper,

View file

@ -9,13 +9,12 @@
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import type { HttpStart } from '@kbn/core-http-browser';
import { ToastsStart } from '@kbn/core-notifications-browser';
import { AlertConsumers } from '@kbn/rule-data-utils';
import { useGetAlertsGroupAggregationsQuery } from './use_get_alerts_group_aggregations_query';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import { BASE_RAC_ALERTS_API_PATH } from '../constants';
const queryClient = new QueryClient({

View file

@ -9,8 +9,7 @@
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import type { HttpStart } from '@kbn/core-http-browser';
import { useHealthCheck } from './use_health_check';

View file

@ -9,8 +9,7 @@
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import { httpServiceMock } from '@kbn/core/public/mocks';
import { useLoadConnectorTypes } from './use_load_connector_types';

View file

@ -9,8 +9,7 @@
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import { httpServiceMock } from '@kbn/core/public/mocks';
import { useLoadConnectors } from './use_load_connectors';

View file

@ -9,8 +9,7 @@
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import { httpServiceMock } from '@kbn/core/public/mocks';
import { useLoadRuleTypeAadTemplateField } from './use_load_rule_type_aad_template_fields';

View file

@ -9,8 +9,7 @@
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import type { HttpStart } from '@kbn/core-http-browser';
import { useResolveRule } from './use_resolve_rule';

View file

@ -12,7 +12,7 @@ import { of } from 'rxjs';
import type { DataPublicPluginStart } from '@kbn/data-plugin/public';
import type { IKibanaSearchResponse } from '@kbn/search-types';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import type { UseSearchAlertsQueryParams } from './use_search_alerts_query';
import { AlertsQueryContext } from '../contexts/alerts_query_context';
import { useSearchAlertsQuery } from './use_search_alerts_query';
@ -126,126 +126,128 @@ describe('useSearchAlertsQuery', () => {
});
it('returns the response correctly', async () => {
const { result, waitForValueToChange } = renderHook(() => useSearchAlertsQuery(params), {
const { result } = renderHook(() => useSearchAlertsQuery(params), {
wrapper,
});
await waitForValueToChange(() => result.current.data);
expect(result.current.data).toEqual(
expect.objectContaining({
...expectedResponse,
alerts: [
{
_index: '.internal.alerts-security.alerts-default-000001',
_id: '38dd308706a127696cc63b8f142e8e4d66f8f79bc7d491dd79a42ea4ead62dd1',
'@timestamp': ['2022-03-22T16:48:07.518Z'],
'host.name': ['Host-4dbzugdlqd'],
'kibana.alert.reason': [
'registry event with process iexlorer.exe, by 5qcxz8o4j7 on Host-4dbzugdlqd created low alert test.',
],
'kibana.alert.risk_score': [21],
'kibana.alert.rule.name': ['test'],
'kibana.alert.severity': ['low'],
'process.name': ['iexlorer.exe'],
'user.name': ['5qcxz8o4j7'],
},
{
_index: '.internal.alerts-security.alerts-default-000001',
_id: '8361363c0db6f30ca2dfb4aeb4835e7d6ec57bc195b96d9ee5a4ead1bb9f8b86',
'@timestamp': ['2022-03-22T16:17:50.769Z'],
'host.name': ['Host-4dbzugdlqd'],
'kibana.alert.reason': [
'network event with process iexlorer.exe, by hdgsmwj08h on Host-4dbzugdlqd created low alert test.',
],
'kibana.alert.risk_score': [21],
'kibana.alert.rule.name': ['test'],
'kibana.alert.severity': ['low'],
'process.name': ['iexlorer.exe'],
'user.name': ['hdgsmwj08h'],
},
],
total: 2,
ecsAlertsData: [
{
kibana: {
alert: {
severity: ['low'],
risk_score: [21],
rule: { name: ['test'] },
reason: [
await waitFor(() => {
expect(result.current.data).toBeDefined();
expect(result.current.data).toEqual(
expect.objectContaining({
...expectedResponse,
alerts: [
{
_index: '.internal.alerts-security.alerts-default-000001',
_id: '38dd308706a127696cc63b8f142e8e4d66f8f79bc7d491dd79a42ea4ead62dd1',
'@timestamp': ['2022-03-22T16:48:07.518Z'],
'host.name': ['Host-4dbzugdlqd'],
'kibana.alert.reason': [
'registry event with process iexlorer.exe, by 5qcxz8o4j7 on Host-4dbzugdlqd created low alert test.',
],
'kibana.alert.risk_score': [21],
'kibana.alert.rule.name': ['test'],
'kibana.alert.severity': ['low'],
'process.name': ['iexlorer.exe'],
'user.name': ['5qcxz8o4j7'],
},
{
_index: '.internal.alerts-security.alerts-default-000001',
_id: '8361363c0db6f30ca2dfb4aeb4835e7d6ec57bc195b96d9ee5a4ead1bb9f8b86',
'@timestamp': ['2022-03-22T16:17:50.769Z'],
'host.name': ['Host-4dbzugdlqd'],
'kibana.alert.reason': [
'network event with process iexlorer.exe, by hdgsmwj08h on Host-4dbzugdlqd created low alert test.',
],
'kibana.alert.risk_score': [21],
'kibana.alert.rule.name': ['test'],
'kibana.alert.severity': ['low'],
'process.name': ['iexlorer.exe'],
'user.name': ['hdgsmwj08h'],
},
],
total: 2,
ecsAlertsData: [
{
kibana: {
alert: {
severity: ['low'],
risk_score: [21],
rule: { name: ['test'] },
reason: [
'registry event with process iexlorer.exe, by 5qcxz8o4j7 on Host-4dbzugdlqd created low alert test.',
],
},
},
process: { name: ['iexlorer.exe'] },
'@timestamp': ['2022-03-22T16:48:07.518Z'],
user: { name: ['5qcxz8o4j7'] },
host: { name: ['Host-4dbzugdlqd'] },
_id: '38dd308706a127696cc63b8f142e8e4d66f8f79bc7d491dd79a42ea4ead62dd1',
_index: '.internal.alerts-security.alerts-default-000001',
},
{
kibana: {
alert: {
severity: ['low'],
risk_score: [21],
rule: { name: ['test'] },
reason: [
'network event with process iexlorer.exe, by hdgsmwj08h on Host-4dbzugdlqd created low alert test.',
],
},
},
process: { name: ['iexlorer.exe'] },
'@timestamp': ['2022-03-22T16:17:50.769Z'],
user: { name: ['hdgsmwj08h'] },
host: { name: ['Host-4dbzugdlqd'] },
_id: '8361363c0db6f30ca2dfb4aeb4835e7d6ec57bc195b96d9ee5a4ead1bb9f8b86',
_index: '.internal.alerts-security.alerts-default-000001',
},
],
oldAlertsData: [
[
{ field: 'kibana.alert.severity', value: ['low'] },
{ field: 'process.name', value: ['iexlorer.exe'] },
{ field: '@timestamp', value: ['2022-03-22T16:48:07.518Z'] },
{ field: 'kibana.alert.risk_score', value: [21] },
{ field: 'kibana.alert.rule.name', value: ['test'] },
{ field: 'user.name', value: ['5qcxz8o4j7'] },
{
field: 'kibana.alert.reason',
value: [
'registry event with process iexlorer.exe, by 5qcxz8o4j7 on Host-4dbzugdlqd created low alert test.',
],
},
},
process: { name: ['iexlorer.exe'] },
'@timestamp': ['2022-03-22T16:48:07.518Z'],
user: { name: ['5qcxz8o4j7'] },
host: { name: ['Host-4dbzugdlqd'] },
_id: '38dd308706a127696cc63b8f142e8e4d66f8f79bc7d491dd79a42ea4ead62dd1',
_index: '.internal.alerts-security.alerts-default-000001',
},
{
kibana: {
alert: {
severity: ['low'],
risk_score: [21],
rule: { name: ['test'] },
reason: [
{ field: 'host.name', value: ['Host-4dbzugdlqd'] },
{
field: '_id',
value: '38dd308706a127696cc63b8f142e8e4d66f8f79bc7d491dd79a42ea4ead62dd1',
},
{ field: '_index', value: '.internal.alerts-security.alerts-default-000001' },
],
[
{ field: 'kibana.alert.severity', value: ['low'] },
{ field: 'process.name', value: ['iexlorer.exe'] },
{ field: '@timestamp', value: ['2022-03-22T16:17:50.769Z'] },
{ field: 'kibana.alert.risk_score', value: [21] },
{ field: 'kibana.alert.rule.name', value: ['test'] },
{ field: 'user.name', value: ['hdgsmwj08h'] },
{
field: 'kibana.alert.reason',
value: [
'network event with process iexlorer.exe, by hdgsmwj08h on Host-4dbzugdlqd created low alert test.',
],
},
},
process: { name: ['iexlorer.exe'] },
'@timestamp': ['2022-03-22T16:17:50.769Z'],
user: { name: ['hdgsmwj08h'] },
host: { name: ['Host-4dbzugdlqd'] },
_id: '8361363c0db6f30ca2dfb4aeb4835e7d6ec57bc195b96d9ee5a4ead1bb9f8b86',
_index: '.internal.alerts-security.alerts-default-000001',
},
],
oldAlertsData: [
[
{ field: 'kibana.alert.severity', value: ['low'] },
{ field: 'process.name', value: ['iexlorer.exe'] },
{ field: '@timestamp', value: ['2022-03-22T16:48:07.518Z'] },
{ field: 'kibana.alert.risk_score', value: [21] },
{ field: 'kibana.alert.rule.name', value: ['test'] },
{ field: 'user.name', value: ['5qcxz8o4j7'] },
{
field: 'kibana.alert.reason',
value: [
'registry event with process iexlorer.exe, by 5qcxz8o4j7 on Host-4dbzugdlqd created low alert test.',
],
},
{ field: 'host.name', value: ['Host-4dbzugdlqd'] },
{
field: '_id',
value: '38dd308706a127696cc63b8f142e8e4d66f8f79bc7d491dd79a42ea4ead62dd1',
},
{ field: '_index', value: '.internal.alerts-security.alerts-default-000001' },
{ field: 'host.name', value: ['Host-4dbzugdlqd'] },
{
field: '_id',
value: '8361363c0db6f30ca2dfb4aeb4835e7d6ec57bc195b96d9ee5a4ead1bb9f8b86',
},
{ field: '_index', value: '.internal.alerts-security.alerts-default-000001' },
],
],
[
{ field: 'kibana.alert.severity', value: ['low'] },
{ field: 'process.name', value: ['iexlorer.exe'] },
{ field: '@timestamp', value: ['2022-03-22T16:17:50.769Z'] },
{ field: 'kibana.alert.risk_score', value: [21] },
{ field: 'kibana.alert.rule.name', value: ['test'] },
{ field: 'user.name', value: ['hdgsmwj08h'] },
{
field: 'kibana.alert.reason',
value: [
'network event with process iexlorer.exe, by hdgsmwj08h on Host-4dbzugdlqd created low alert test.',
],
},
{ field: 'host.name', value: ['Host-4dbzugdlqd'] },
{
field: '_id',
value: '8361363c0db6f30ca2dfb4aeb4835e7d6ec57bc195b96d9ee5a4ead1bb9f8b86',
},
{ field: '_index', value: '.internal.alerts-security.alerts-default-000001' },
],
],
})
);
})
);
});
});
it('returns empty placeholder data', () => {

View file

@ -9,8 +9,7 @@
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import type { HttpStart } from '@kbn/core-http-browser';
import { useUpdateRule } from './use_update_rule';

View file

@ -9,7 +9,7 @@
import React, { FunctionComponent } from 'react';
import * as ReactQuery from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { testQueryClientConfig } from '../test_utils/test_query_client_config';
import { queryKeyPrefix, useVirtualDataViewQuery } from './use_virtual_data_view_query';
import { DataView } from '@kbn/data-views-plugin/common';
@ -38,10 +38,11 @@ describe('useVirtualDataViewQuery', () => {
it('does not create a data view if indexNames is empty or nullish', () => {
const { rerender } = renderHook(
({ indexNames }: React.PropsWithChildren<{ indexNames: string[] }>) =>
({ indexNames }: { indexNames?: string[] }) =>
useVirtualDataViewQuery({ dataViewsService: mockDataViewsService, indexNames }),
{
wrapper,
initialProps: {},
}
);
@ -89,7 +90,7 @@ describe('useVirtualDataViewQuery', () => {
});
it('removes the data view from the instance cache on unmount', async () => {
const { result, waitForValueToChange, unmount } = renderHook(
const { result, unmount } = renderHook(
() =>
useVirtualDataViewQuery({
dataViewsService: mockDataViewsService,
@ -100,10 +101,10 @@ describe('useVirtualDataViewQuery', () => {
}
);
await waitForValueToChange(() => result.current.data);
await waitFor(() => expect(result.current.data).toBeDefined());
unmount();
expect(mockDataViewsService.clearInstanceCache).toHaveBeenCalled();
await waitFor(() => expect(mockDataViewsService.clearInstanceCache).toHaveBeenCalled());
});
});

View file

@ -9,8 +9,7 @@
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import type { HttpStart } from '@kbn/core-http-browser';
import type { ToastsStart } from '@kbn/core-notifications-browser';

View file

@ -8,7 +8,7 @@
*/
import React, { useReducer } from 'react';
import { act, renderHook } from '@testing-library/react-hooks/dom';
import { renderHook, act } from '@testing-library/react';
import { ruleFormStateReducer } from './rule_form_state_reducer';
import { RuleFormState } from '../types';
import { getAction } from '../../common/test_utils/actions_test_utils';

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useReducer } from 'react';
import { groupActions, groupsReducerWithStorage, initialState } from '.';
import { defaultGroup, LOCAL_STORAGE_GROUPING_KEY } from '../..';

View file

@ -7,7 +7,7 @@
* License v3.0 only", or the "Server Side Public License, v 1".
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useGetGroupSelector, useGetGroupSelectorStateless } from './use_get_group_selector';
import { initialState } from './state';

View file

@ -8,9 +8,8 @@
*/
import React from 'react';
import { act, renderHook } from '@testing-library/react-hooks';
import { __IntlProvider as IntlProvider } from '@kbn/i18n-react';
import { render } from '@testing-library/react';
import { render, waitFor, renderHook } from '@testing-library/react';
import { useGrouping } from './use_grouping';
@ -46,92 +45,86 @@ const groupingArgs = {
describe('useGrouping', () => {
it('Renders child component without grouping table wrapper when no group is selected', async () => {
await act(async () => {
const { result, waitForNextUpdate } = renderHook(() => useGrouping(defaultArgs));
await waitForNextUpdate();
await waitForNextUpdate();
const { getByTestId, queryByTestId } = render(
<IntlProvider locale="en">
{result.current.getGrouping({
...groupingArgs,
data: {
groupsCount: {
value: 9,
},
groupByFields: {
buckets: [
{
key: ['critical hosts', 'description'],
key_as_string: 'critical hosts|description',
doc_count: 3,
unitsCount: {
value: 3,
},
},
],
},
unitsCount: {
value: 18,
},
const { result } = renderHook(() => useGrouping(defaultArgs));
await waitFor(() => new Promise((resolve) => resolve(null)));
const { getByTestId, queryByTestId } = render(
<IntlProvider locale="en">
{result.current.getGrouping({
...groupingArgs,
data: {
groupsCount: {
value: 9,
},
renderChildComponent: () => <p data-test-subj="innerTable">{'hello'}</p>,
selectedGroup: 'none',
})}
</IntlProvider>
);
groupByFields: {
buckets: [
{
key: ['critical hosts', 'description'],
key_as_string: 'critical hosts|description',
doc_count: 3,
unitsCount: {
value: 3,
},
},
],
},
unitsCount: {
value: 18,
},
},
renderChildComponent: () => <p data-test-subj="innerTable">{'hello'}</p>,
selectedGroup: 'none',
})}
</IntlProvider>
);
expect(getByTestId('innerTable')).toBeInTheDocument();
expect(queryByTestId('grouping-table')).not.toBeInTheDocument();
});
expect(getByTestId('innerTable')).toBeInTheDocument();
expect(queryByTestId('grouping-table')).not.toBeInTheDocument();
});
it('Renders child component with grouping table wrapper when group is selected', async () => {
await act(async () => {
const getItem = jest.spyOn(window.localStorage.__proto__, 'getItem');
getItem.mockReturnValue(
JSON.stringify({
'test-table': {
itemsPerPageOptions: [10, 25, 50, 100],
itemsPerPage: 25,
activeGroup: 'kibana.alert.rule.name',
options: defaultGroupingOptions,
},
})
);
const getItem = jest.spyOn(window.localStorage.__proto__, 'getItem');
getItem.mockReturnValue(
JSON.stringify({
'test-table': {
itemsPerPageOptions: [10, 25, 50, 100],
itemsPerPage: 25,
activeGroup: 'kibana.alert.rule.name',
options: defaultGroupingOptions,
},
})
);
const { result, waitForNextUpdate } = renderHook(() => useGrouping(defaultArgs));
await waitForNextUpdate();
await waitForNextUpdate();
const { getByTestId } = render(
<IntlProvider locale="en">
{result.current.getGrouping({
...groupingArgs,
data: {
groupsCount: {
value: 9,
},
groupByFields: {
buckets: [
{
key: ['critical hosts', 'description'],
key_as_string: 'critical hosts|description',
doc_count: 3,
unitsCount: {
value: 3,
},
},
],
},
unitsCount: {
value: 18,
},
const { result } = renderHook(() => useGrouping(defaultArgs));
await waitFor(() => new Promise((resolve) => resolve(null)));
const { getByTestId } = render(
<IntlProvider locale="en">
{result.current.getGrouping({
...groupingArgs,
data: {
groupsCount: {
value: 9,
},
renderChildComponent: jest.fn(),
selectedGroup: 'test',
})}
</IntlProvider>
);
groupByFields: {
buckets: [
{
key: ['critical hosts', 'description'],
key_as_string: 'critical hosts|description',
doc_count: 3,
unitsCount: {
value: 3,
},
},
],
},
unitsCount: {
value: 18,
},
},
renderChildComponent: jest.fn(),
selectedGroup: 'test',
})}
</IntlProvider>
);
expect(getByTestId('grouping-table')).toBeInTheDocument();
});
expect(getByTestId('grouping-table')).toBeInTheDocument();
});
});

View file

@ -4,8 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook, act } from '@testing-library/react';
import { AppMockRenderer, createAppMockRenderer } from '../lib/test_utils';
import { useArchiveMaintenanceWindow } from './use_archive_maintenance_window';

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useBreadcrumbs } from './use_breadcrumbs';
import { MAINTENANCE_WINDOW_DEEP_LINK_IDS } from '../../common';
import { AppMockRenderer, createAppMockRenderer } from '../lib/test_utils';

View file

@ -4,8 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook, act } from '@testing-library/react';
import { AppMockRenderer, createAppMockRenderer } from '../lib/test_utils';
import { useCreateMaintenanceWindow } from './use_create_maintenance_window';

View file

@ -4,8 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import { AppMockRenderer, createAppMockRenderer } from '../lib/test_utils';
import { useFindMaintenanceWindows } from './use_find_maintenance_windows';

View file

@ -4,8 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook, act } from '@testing-library/react';
import { AppMockRenderer, createAppMockRenderer } from '../lib/test_utils';
import { useFinishAndArchiveMaintenanceWindow } from './use_finish_and_archive_maintenance_window';

View file

@ -4,8 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook, act } from '@testing-library/react';
import { AppMockRenderer, createAppMockRenderer } from '../lib/test_utils';
import { useFinishMaintenanceWindow } from './use_finish_maintenance_window';

View file

@ -4,8 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import { AppMockRenderer, createAppMockRenderer } from '../lib/test_utils';
import { useGetMaintenanceWindow } from './use_get_maintenance_window';

View file

@ -6,7 +6,7 @@
*/
import { licensingMock } from '@kbn/licensing-plugin/public/mocks';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useLicense } from './use_license';
import { AppMockRenderer, createAppMockRenderer } from '../lib/test_utils';

View file

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

View file

@ -4,8 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks/dom';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook, act } from '@testing-library/react';
import { AppMockRenderer, createAppMockRenderer } from '../lib/test_utils';
import { useUpdateMaintenanceWindow } from './use_update_maintenance_window';

View file

@ -5,12 +5,8 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import type { CaseAttachmentsWithoutOwner } from '../../types';
import type {
StartAddAttachmentToExistingCaseTransaction,
StartCreateCaseWithAttachmentsTransaction,
} from './use_cases_transactions';
import {
useAddAttachmentToExistingCaseTransaction,
useCreateCaseWithAttachmentsTransaction,
@ -37,14 +33,10 @@ const bulkAttachments = [
] as CaseAttachmentsWithoutOwner;
const renderUseCreateCaseWithAttachmentsTransaction = () =>
renderHook<void, { startTransaction: StartCreateCaseWithAttachmentsTransaction }>(
useCreateCaseWithAttachmentsTransaction
);
renderHook(useCreateCaseWithAttachmentsTransaction);
const renderUseAddAttachmentToExistingCaseTransaction = () =>
renderHook<void, { startTransaction: StartAddAttachmentToExistingCaseTransaction }>(
useAddAttachmentToExistingCaseTransaction
);
renderHook(useAddAttachmentToExistingCaseTransaction);
describe('cases transactions', () => {
beforeEach(() => {

View file

@ -6,7 +6,7 @@
*/
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { TestProviders } from './mock';
import { useIsMainApplication } from './hooks';

View file

@ -6,7 +6,7 @@
*/
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useApplicationCapabilities } from './hooks';
import { allCasesPermissions, TestProviders } from '../../mock';
@ -14,10 +14,7 @@ import { allCasesPermissions, TestProviders } from '../../mock';
describe('hooks', () => {
describe('useApplicationCapabilities', () => {
it('should return the correct capabilities', async () => {
const { result } = renderHook<
React.PropsWithChildren<{}>,
ReturnType<typeof useApplicationCapabilities>
>(() => useApplicationCapabilities(), {
const { result } = renderHook(() => useApplicationCapabilities(), {
wrapper: ({ children }) => <TestProviders>{children}</TestProviders>,
});

View file

@ -7,7 +7,7 @@
import type { PublicAppInfo } from '@kbn/core-application-browser';
import { AppStatus } from '@kbn/core-application-browser';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { BehaviorSubject, Subject } from 'rxjs';
import type { AppMockRenderer } from '../../mock';
import { createAppMockRenderer } from '../../mock';

View file

@ -6,7 +6,8 @@
*/
import React from 'react';
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { APP_ID } from '../../../common/constants';
import { useNavigation } from '../lib/kibana';

View file

@ -6,10 +6,9 @@
*/
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { licensingMock } from '@kbn/licensing-plugin/public/mocks';
import type { CasesContextFeatures } from '../../common/ui';
import type { UseCasesFeatures } from './use_cases_features';
import { useCasesFeatures } from './use_cases_features';
import { TestProviders } from './mock/test_providers';
import type { LicenseType } from '@kbn/licensing-plugin/common/types';
@ -37,14 +36,9 @@ describe('useCasesFeatures', () => {
it.each(tests)(
'returns isAlertsEnabled=%s and isSyncAlertsEnabled=%s if feature.alerts=%s',
async (isAlertsEnabled, isSyncAlertsEnabled, alerts) => {
const { result } = renderHook<React.PropsWithChildren<{}>, UseCasesFeatures>(
() => useCasesFeatures(),
{
wrapper: ({ children }) => (
<TestProviders features={{ alerts }}>{children}</TestProviders>
),
}
);
const { result } = renderHook(() => useCasesFeatures(), {
wrapper: ({ children }) => <TestProviders features={{ alerts }}>{children}</TestProviders>,
});
expect(result.current).toEqual({
isAlertsEnabled,
@ -57,16 +51,13 @@ describe('useCasesFeatures', () => {
);
it('returns the metrics correctly', async () => {
const { result } = renderHook<React.PropsWithChildren<{}>, UseCasesFeatures>(
() => useCasesFeatures(),
{
wrapper: ({ children }) => (
<TestProviders features={{ metrics: [CaseMetricsFeature.CONNECTORS] }}>
{children}
</TestProviders>
),
}
);
const { result } = renderHook(() => useCasesFeatures(), {
wrapper: ({ children }) => (
<TestProviders features={{ metrics: [CaseMetricsFeature.CONNECTORS] }}>
{children}
</TestProviders>
),
});
expect(result.current).toEqual({
isAlertsEnabled: true,
@ -91,12 +82,9 @@ describe('useCasesFeatures', () => {
license: { type },
});
const { result } = renderHook<React.PropsWithChildren<{}>, UseCasesFeatures>(
() => useCasesFeatures(),
{
wrapper: ({ children }) => <TestProviders license={license}>{children}</TestProviders>,
}
);
const { result } = renderHook(() => useCasesFeatures(), {
wrapper: ({ children }) => <TestProviders license={license}>{children}</TestProviders>,
});
expect(result.current).toEqual({
isAlertsEnabled: true,

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { Subject } from 'rxjs';
import type { AppMockRenderer } from './mock/test_providers';
import { createAppMockRenderer } from './mock/test_providers';

View file

@ -5,7 +5,6 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { useKibana, useToasts } from './lib/kibana';
import type { AppMockRenderer } from './mock';
import { createAppMockRenderer, TestProviders } from './mock';
@ -14,7 +13,7 @@ import { alertComment, basicComment, mockCase } from '../containers/mock';
import React from 'react';
import userEvent from '@testing-library/user-event';
import type { SupportedCaseAttachment } from '../types';
import { getByTestId, queryByTestId, screen } from '@testing-library/react';
import { getByTestId, queryByTestId, screen, renderHook } from '@testing-library/react';
import { OWNER_INFO } from '../../common/constants';
import { useApplication } from './lib/kibana/use_application';

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import type { AppMockRenderer } from './mock';
import { createAppMockRenderer } from './mock';
import { useIsUserTyping } from './use_is_user_typing';

View file

@ -7,7 +7,7 @@
import React from 'react';
import { licensingMock } from '@kbn/licensing-plugin/public/mocks';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { TestProviders } from './mock';
import { useLicense } from './use_license';

View file

@ -7,7 +7,7 @@
import type { AppMockRenderer } from '../../../common/mock';
import { createAppMockRenderer } from '../../../common/mock';
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { useAssigneesAction } from './use_assignees_action';
import * as api from '../../../containers/api';
@ -56,7 +56,7 @@ describe('useAssigneesAction', () => {
it('update the assignees correctly', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useAssigneesAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -92,7 +92,7 @@ describe('useAssigneesAction', () => {
});
it('shows the success toaster correctly when updating one case', async () => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useAssigneesAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -118,7 +118,7 @@ describe('useAssigneesAction', () => {
});
it('shows the success toaster correctly when updating multiple cases', async () => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useAssigneesAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,

View file

@ -7,7 +7,7 @@
import type { AppMockRenderer } from '../../../common/mock';
import { createAppMockRenderer } from '../../../common/mock';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useCopyIDAction } from './use_copy_id_action';
import { basicCase } from '../../../containers/mock';
@ -58,7 +58,7 @@ describe('useCopyIDAction', () => {
});
it('copies the id of the selected case to the clipboard', async () => {
const { result, waitFor } = renderHook(() => useCopyIDAction({ onActionSuccess }), {
const { result } = renderHook(() => useCopyIDAction({ onActionSuccess }), {
wrapper: appMockRender.AppWrapper,
});
@ -73,7 +73,7 @@ describe('useCopyIDAction', () => {
});
it('shows the success toaster correctly when copying the case id', async () => {
const { result, waitFor } = renderHook(() => useCopyIDAction({ onActionSuccess }), {
const { result } = renderHook(() => useCopyIDAction({ onActionSuccess }), {
wrapper: appMockRender.AppWrapper,
});

View file

@ -7,7 +7,7 @@
import type { AppMockRenderer } from '../../../common/mock';
import { createAppMockRenderer } from '../../../common/mock';
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { useDeleteAction } from './use_delete_action';
import * as api from '../../../containers/api';
@ -84,7 +84,7 @@ describe('useDeleteAction', () => {
it('deletes the selected cases', async () => {
const deleteSpy = jest.spyOn(api, 'deleteCases');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useDeleteAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -112,7 +112,7 @@ describe('useDeleteAction', () => {
});
it('closes the modal', async () => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useDeleteAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -137,7 +137,7 @@ describe('useDeleteAction', () => {
});
it('shows the success toaster correctly when delete one case', async () => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useDeleteAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -163,7 +163,7 @@ describe('useDeleteAction', () => {
});
it('shows the success toaster correctly when delete multiple case', async () => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useDeleteAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,

View file

@ -7,7 +7,7 @@
import type { AppMockRenderer } from '../../../common/mock';
import { createAppMockRenderer } from '../../../common/mock';
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { useSeverityAction } from './use_severity_action';
import * as api from '../../../containers/api';
@ -80,7 +80,7 @@ describe('useSeverityAction', () => {
it('update the severity cases', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useSeverityAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -120,7 +120,7 @@ describe('useSeverityAction', () => {
it.each(singleCaseTests)(
'shows the success toaster correctly when updating the severity of the case: %s',
async (_, index, expectedMessage) => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useSeverityAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -153,7 +153,7 @@ describe('useSeverityAction', () => {
it.each(multipleCasesTests)(
'shows the success toaster correctly when updating the severity of the case: %s',
async (_, index, expectedMessage) => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useSeverityAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,

View file

@ -7,7 +7,7 @@
import type { AppMockRenderer } from '../../../common/mock';
import { createAppMockRenderer } from '../../../common/mock';
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { useStatusAction } from './use_status_action';
import * as api from '../../../containers/api';
@ -82,7 +82,7 @@ describe('useStatusAction', () => {
it('update the status cases', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useStatusAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -120,7 +120,7 @@ describe('useStatusAction', () => {
it.each(singleCaseTests)(
'shows the success toaster correctly when updating the status of the case: %s',
async (_, index, expectedMessage) => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useStatusAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -152,7 +152,7 @@ describe('useStatusAction', () => {
it.each(multipleCasesTests)(
'shows the success toaster correctly when updating the status of the case: %s',
async (_, index, expectedMessage) => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useStatusAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,

View file

@ -7,7 +7,7 @@
import type { AppMockRenderer } from '../../../common/mock';
import { createAppMockRenderer } from '../../../common/mock';
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { useTagsAction } from './use_tags_action';
import * as api from '../../../containers/api';
@ -56,7 +56,7 @@ describe('useTagsAction', () => {
it('update the tags correctly', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useTagsAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -86,7 +86,7 @@ describe('useTagsAction', () => {
});
it('shows the success toaster correctly when updating one case', async () => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useTagsAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,
@ -112,7 +112,7 @@ describe('useTagsAction', () => {
});
it('shows the success toaster correctly when updating multiple cases', async () => {
const { result, waitFor } = renderHook(
const { result } = renderHook(
() => useTagsAction({ onAction, onActionSuccess, isDisabled: false }),
{
wrapper: appMockRender.AppWrapper,

View file

@ -7,7 +7,7 @@
import type { AppMockRenderer } from '../../common/mock';
import { createAppMockRenderer } from '../../common/mock';
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { useItemsAction } from './use_items_action';
import * as api from '../../containers/api';
@ -54,7 +54,7 @@ describe('useItemsAction', () => {
});
it('closes the flyout', async () => {
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});
@ -81,7 +81,7 @@ describe('useItemsAction', () => {
it('update the items correctly', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});
@ -117,7 +117,7 @@ describe('useItemsAction', () => {
});
it('calls fieldSelector correctly', async () => {
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});
@ -142,7 +142,7 @@ describe('useItemsAction', () => {
});
it('calls itemsTransformer correctly', async () => {
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});
@ -169,7 +169,7 @@ describe('useItemsAction', () => {
it('removes duplicates', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});
@ -203,7 +203,7 @@ describe('useItemsAction', () => {
});
it('shows the success toaster correctly when updating a case', async () => {
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});
@ -229,7 +229,7 @@ describe('useItemsAction', () => {
it('do not update cases with no changes', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});
@ -254,7 +254,7 @@ describe('useItemsAction', () => {
it('do not update if the selected items are the same but with different order', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});
@ -279,7 +279,7 @@ describe('useItemsAction', () => {
it('do not update if the selected items are the same', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});
@ -304,7 +304,7 @@ describe('useItemsAction', () => {
it('do not update if selecting and unselecting the same item', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});
@ -329,7 +329,7 @@ describe('useItemsAction', () => {
it('do not update with empty items and no selection', async () => {
const updateSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor } = renderHook(() => useItemsAction(props), {
const { result } = renderHook(() => useItemsAction(props), {
wrapper: appMockRender.AppWrapper,
});

View file

@ -7,7 +7,7 @@
import type { AppMockRenderer } from '../../common/mock';
import { createAppMockRenderer } from '../../common/mock';
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useItemsState } from './use_items_state';
import { basicCase } from '../../containers/mock';

View file

@ -7,8 +7,7 @@
import React from 'react';
import moment from 'moment-timezone';
import { render, waitFor, screen, within } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks';
import { render, waitFor, screen, within, renderHook } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { waitForEuiPopoverOpen } from '@elastic/eui/lib/test/rtl';
@ -27,7 +26,6 @@ import { SECURITY_SOLUTION_OWNER } from '../../../common/constants';
import { getEmptyCellValue } from '../empty_value';
import { useKibana } from '../../common/lib/kibana';
import { AllCasesList } from './all_cases_list';
import type { GetCasesColumn, UseCasesColumnsReturnValue } from './use_cases_columns';
import { useCasesColumns } from './use_cases_columns';
import { triggersActionsUiMock } from '@kbn/triggers-actions-ui-plugin/public/mocks';
import { registerConnectorsToMockActionRegistry } from '../../common/mock/register_connectors';
@ -267,10 +265,7 @@ describe.skip('AllCasesListGeneric', () => {
expect(column[key].querySelector('span')).toHaveTextContent(emptyTag);
};
const { result } = renderHook<
React.PropsWithChildren<GetCasesColumn>,
UseCasesColumnsReturnValue
>(() => useCasesColumns(defaultColumnArgs), {
const { result } = renderHook(() => useCasesColumns(defaultColumnArgs), {
wrapper: ({ children }) => <TestProviders>{children}</TestProviders>,
});

View file

@ -5,8 +5,7 @@
* 2.0.
*/
import { waitFor } from '@testing-library/react';
import { act, renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import type { FC, PropsWithChildren } from 'react';
import React from 'react';
@ -96,12 +95,11 @@ describe('use cases add to existing case modal hook', () => {
});
it('should throw if called outside of a cases context', () => {
const { result } = renderHook(() => {
useCasesAddToExistingCaseModal(defaultParams());
});
expect(result.error?.message).toContain(
'useCasesContext must be used within a CasesProvider and have a defined value'
);
expect(() =>
renderHook(() => {
useCasesAddToExistingCaseModal(defaultParams());
})
).toThrow(/useCasesContext must be used within a CasesProvider and have a defined value/);
});
it('should dispatch the open action when invoked', () => {

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import type { AppMockRenderer } from '../../../common/mock';
import { createAppMockRenderer } from '../../../common/mock';
import type { FilterConfig, FilterConfigRenderParams } from './types';
@ -64,7 +64,7 @@ describe('useFilterConfig', () => {
it('should remove a selected option if the filter is deleted', async () => {
const { rerender } = renderHook(useFilterConfig, {
wrapper: ({ children }: React.PropsWithChildren<Parameters<typeof useFilterConfig>[0]>) => (
wrapper: ({ children }: React.PropsWithChildren) => (
<appMockRender.AppWrapper>{children}</appMockRender.AppWrapper>
),
initialProps: {
@ -106,7 +106,7 @@ describe('useFilterConfig', () => {
);
const { result } = renderHook(useFilterConfig, {
wrapper: ({ children }: React.PropsWithChildren<Parameters<typeof useFilterConfig>[0]>) => (
wrapper: ({ children }: React.PropsWithChildren) => (
<appMockRender.AppWrapper>{children}</appMockRender.AppWrapper>
),
initialProps: {

View file

@ -6,8 +6,7 @@
*/
import userEvent, { type UserEvent } from '@testing-library/user-event';
import { waitFor } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor, renderHook } from '@testing-library/react';
import {
waitForEuiPopoverOpen,
waitForEuiContextMenuPanelTransition,

View file

@ -6,8 +6,7 @@
*/
import React from 'react';
import { renderHook, act } from '@testing-library/react-hooks';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook, act } from '@testing-library/react';
import { CaseStatuses } from '@kbn/cases-components';
import { TestProviders } from '../../common/mock';

View file

@ -8,8 +8,7 @@
import React from 'react';
import { EuiContextMenu } from '@elastic/eui';
import userEvent from '@testing-library/user-event';
import { waitFor } from '@testing-library/react';
import { renderHook } from '@testing-library/react-hooks/dom';
import { waitFor, renderHook } from '@testing-library/react';
import type { AppMockRenderer } from '../../common/mock';
import {
@ -190,7 +189,7 @@ describe('useBulkActions', () => {
it('change the status of cases', async () => {
const updateCasesSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor: waitForHook } = renderHook(
const { result } = renderHook(
() => useBulkActions({ onAction, onActionSuccess, selectedCases: [basicCase] }),
{
wrapper: appMockRender.AppWrapper,
@ -219,7 +218,7 @@ describe('useBulkActions', () => {
pointerEventsCheck: 0,
});
await waitForHook(() => {
await waitFor(() => {
expect(updateCasesSpy).toHaveBeenCalled();
});
});
@ -227,7 +226,7 @@ describe('useBulkActions', () => {
it('change the severity of cases', async () => {
const updateCasesSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor: waitForHook } = renderHook(
const { result } = renderHook(
() => useBulkActions({ onAction, onActionSuccess, selectedCases: [basicCase] }),
{
wrapper: appMockRender.AppWrapper,
@ -257,7 +256,7 @@ describe('useBulkActions', () => {
pointerEventsCheck: 0,
});
await waitForHook(() => {
await waitFor(() => {
expect(updateCasesSpy).toHaveBeenCalled();
});
});
@ -266,7 +265,7 @@ describe('useBulkActions', () => {
it('delete a case', async () => {
const deleteSpy = jest.spyOn(api, 'deleteCases');
const { result, waitFor: waitForHook } = renderHook(
const { result } = renderHook(
() => useBulkActions({ onAction, onActionSuccess, selectedCases: [basicCase] }),
{
wrapper: appMockRender.AppWrapper,
@ -299,7 +298,7 @@ describe('useBulkActions', () => {
await userEvent.click(res.getByTestId('confirmModalConfirmButton'));
await waitForHook(() => {
await waitFor(() => {
expect(deleteSpy).toHaveBeenCalled();
});
});
@ -355,7 +354,7 @@ describe('useBulkActions', () => {
it('change the tags of the case', async () => {
const updateCasesSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor: waitForHook } = renderHook(
const { result } = renderHook(
() => useBulkActions({ onAction, onActionSuccess, selectedCases: [basicCase] }),
{
wrapper: appMockRender.AppWrapper,
@ -394,7 +393,7 @@ describe('useBulkActions', () => {
await userEvent.click(res.getByText('coke'));
await userEvent.click(res.getByTestId('cases-edit-tags-flyout-submit'));
await waitForHook(() => {
await waitFor(() => {
expect(updateCasesSpy).toHaveBeenCalled();
});
});
@ -402,7 +401,7 @@ describe('useBulkActions', () => {
it('change the assignees of the case', async () => {
const updateCasesSpy = jest.spyOn(api, 'updateCases');
const { result, waitFor: waitForHook } = renderHook(
const { result } = renderHook(
() => useBulkActions({ onAction, onActionSuccess, selectedCases: [basicCase] }),
{
wrapper: appMockRender.AppWrapper,
@ -441,7 +440,7 @@ describe('useBulkActions', () => {
await userEvent.click(res.getByText('Damaged Raccoon'));
await userEvent.click(res.getByTestId('cases-edit-assignees-flyout-submit'));
await waitForHook(() => {
await waitFor(() => {
expect(updateCasesSpy).toHaveBeenCalled();
});
});
@ -450,7 +449,7 @@ describe('useBulkActions', () => {
describe('Permissions', () => {
it('shows the correct actions with all permissions', async () => {
appMockRender = createAppMockRenderer({ permissions: allCasesPermissions() });
const { result, waitFor: waitForHook } = renderHook(
const { result } = renderHook(
() => useBulkActions({ onAction, onActionSuccess, selectedCases: [basicCase] }),
{
wrapper: appMockRender.AppWrapper,
@ -467,7 +466,7 @@ describe('useBulkActions', () => {
</>
);
await waitForHook(() => {
await waitFor(() => {
expect(res.getByTestId('case-bulk-action-status')).toBeInTheDocument();
expect(res.getByTestId('cases-bulk-action-delete')).toBeInTheDocument();
expect(res.getByTestId('bulk-actions-separator')).toBeInTheDocument();
@ -476,7 +475,7 @@ describe('useBulkActions', () => {
it('shows the correct actions with no delete permissions', async () => {
appMockRender = createAppMockRenderer({ permissions: noDeleteCasesPermissions() });
const { result, waitFor: waitForHook } = renderHook(
const { result } = renderHook(
() => useBulkActions({ onAction, onActionSuccess, selectedCases: [basicCase] }),
{
wrapper: appMockRender.AppWrapper,
@ -493,7 +492,7 @@ describe('useBulkActions', () => {
</>
);
await waitForHook(() => {
await waitFor(() => {
expect(res.getByTestId('case-bulk-action-status')).toBeInTheDocument();
expect(res.queryByTestId('cases-bulk-action-delete')).toBeFalsy();
expect(res.queryByTestId('bulk-actions-separator')).toBeFalsy();
@ -502,7 +501,7 @@ describe('useBulkActions', () => {
it('shows the correct actions with only delete permissions', async () => {
appMockRender = createAppMockRenderer({ permissions: onlyDeleteCasesPermission() });
const { result, waitFor: waitForHook } = renderHook(
const { result } = renderHook(
() => useBulkActions({ onAction, onActionSuccess, selectedCases: [basicCase] }),
{
wrapper: appMockRender.AppWrapper,
@ -519,7 +518,7 @@ describe('useBulkActions', () => {
</>
);
await waitForHook(() => {
await waitFor(() => {
expect(res.queryByTestId('case-bulk-action-status')).toBeFalsy();
expect(res.getByTestId('cases-bulk-action-delete')).toBeInTheDocument();
expect(res.queryByTestId('bulk-actions-separator')).toBeFalsy();
@ -528,7 +527,7 @@ describe('useBulkActions', () => {
it('shows the correct actions with no reopen permissions', async () => {
appMockRender = createAppMockRenderer({ permissions: noReopenCasesPermissions() });
const { result, waitFor: waitForHook } = renderHook(
const { result } = renderHook(
() => useBulkActions({ onAction, onActionSuccess, selectedCases: [basicCaseClosed] }),
{
wrapper: appMockRender.AppWrapper,
@ -545,12 +544,12 @@ describe('useBulkActions', () => {
</>
);
await waitForHook(() => {
await waitFor(() => {
expect(res.queryByTestId('case-bulk-action-status')).toBeInTheDocument();
res.queryByTestId('case-bulk-action-status')?.click();
});
await waitForHook(() => {
await waitFor(() => {
expect(res.queryByTestId('cases-bulk-action-status-open')).toBeDisabled();
expect(res.queryByTestId('cases-bulk-action-status-in-progress')).toBeDisabled();
expect(res.queryByTestId('cases-bulk-action-status-closed')).toBeDisabled();

View file

@ -15,7 +15,7 @@ import { useGetCasesMockState } from '../../containers/mock';
import { connectors, useCaseConfigureResponse } from '../configure_cases/__mock__';
import type { AppMockRenderer } from '../../common/mock';
import { createAppMockRenderer, readCasesPermissions, TestProviders } from '../../common/mock';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { CaseStatuses, CustomFieldTypes } from '../../../common/types/domain';
import { userProfilesMap } from '../../containers/user_profiles/api.mock';
import { useGetCaseConfiguration } from '../../containers/configure/use_get_case_configuration';

View file

@ -6,7 +6,7 @@
*/
import { licensingMock } from '@kbn/licensing-plugin/public/mocks';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import type { AppMockRenderer } from '../../common/mock';
import { createAppMockRenderer } from '../../common/mock';

View file

@ -6,7 +6,7 @@
*/
import { licensingMock } from '@kbn/licensing-plugin/public/mocks';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import type { AppMockRenderer } from '../../common/mock';

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import type { AppMockRenderer } from '../../common/mock';
import { createAppMockRenderer } from '../../common/mock';
import { casesQueriesKeys } from '../../containers/constants';

View file

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

View file

@ -6,7 +6,7 @@
*/
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useKibana } from '../../common/lib/kibana';
import { readCasesPermissions, TestProviders } from '../../common/mock';

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useCasesAddToExistingCaseModal } from '../../all_cases/selector_modal/use_cases_add_to_existing_case_modal';
import { createAppMockRenderer } from '../../../common/mock';
import { useIsAddToCaseOpen } from './use_is_add_to_case_open';
@ -26,9 +26,8 @@ describe('use is add to existing case modal open hook', () => {
});
it('should throw if called outside of a cases context', () => {
const { result } = renderHook(useIsAddToCaseOpen);
expect(result.error?.message).toContain(
'useCasesStateContext must be used within a CasesProvider and have a defined value'
expect(() => renderHook(useIsAddToCaseOpen)).toThrow(
/useCasesStateContext must be used within a CasesProvider and have a defined value/
);
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useKibana, useToasts } from '../../../common/lib/kibana';
import { connector } from '../mock';
@ -30,7 +30,7 @@ describe('useGetFieldsByIssueType', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'getFieldsByIssueType');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useGetFieldsByIssueType({
http,
@ -88,7 +88,7 @@ describe('useGetFieldsByIssueType', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { waitFor } = renderHook(
renderHook(
() =>
useGetFieldsByIssueType({
http,
@ -114,7 +114,7 @@ describe('useGetFieldsByIssueType', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { waitFor } = renderHook(
renderHook(
() =>
useGetFieldsByIssueType({
http,

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useKibana, useToasts } from '../../../common/lib/kibana';
import { connector as actionConnector } from '../mock';
@ -30,7 +30,7 @@ describe('useGetIssue', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'getIssue');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useGetIssue({
http,
@ -40,7 +40,7 @@ describe('useGetIssue', () => {
{ wrapper: appMockRender.AppWrapper }
);
await waitFor(() => result.current.isSuccess);
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(spy).toHaveBeenCalledWith({
http,
@ -88,7 +88,7 @@ describe('useGetIssue', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useGetIssue({
http,
@ -98,9 +98,10 @@ describe('useGetIssue', () => {
{ wrapper: appMockRender.AppWrapper }
);
await waitFor(() => result.current.isError);
expect(addError).toHaveBeenCalled();
await waitFor(() => {
expect(result.current.isError).toBe(true);
expect(addError).toHaveBeenCalled();
});
});
it('calls addError when the getIssue api returns successfully but contains an error', async () => {
@ -114,7 +115,7 @@ describe('useGetIssue', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useGetIssue({
http,
@ -124,8 +125,9 @@ describe('useGetIssue', () => {
{ wrapper: appMockRender.AppWrapper }
);
await waitFor(() => result.current.isSuccess);
expect(addError).toHaveBeenCalled();
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
expect(addError).toHaveBeenCalled();
});
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useKibana, useToasts } from '../../../common/lib/kibana';
import { connector } from '../mock';
@ -30,7 +30,7 @@ describe('useGetIssueTypes', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'getIssueTypes');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useGetIssueTypes({
http,
@ -70,7 +70,7 @@ describe('useGetIssueTypes', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { waitFor } = renderHook(
renderHook(
() =>
useGetIssueTypes({
http,
@ -95,7 +95,7 @@ describe('useGetIssueTypes', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { waitFor } = renderHook(
renderHook(
() =>
useGetIssueTypes({
http,

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useKibana, useToasts } from '../../../common/lib/kibana';
import { connector as actionConnector } from '../mock';
@ -30,7 +30,7 @@ describe('useGetIssues', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'getIssues');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useGetIssues({
http,
@ -40,13 +40,14 @@ describe('useGetIssues', () => {
{ wrapper: appMockRender.AppWrapper }
);
await waitFor(() => result.current.isSuccess);
expect(spy).toHaveBeenCalledWith({
http,
signal: expect.anything(),
connectorId: actionConnector.id,
title: 'Task',
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
expect(spy).toHaveBeenCalledWith({
http,
signal: expect.anything(),
connectorId: actionConnector.id,
title: 'Task',
});
});
});
@ -74,7 +75,7 @@ describe('useGetIssues', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useGetIssues({
http,
@ -84,9 +85,10 @@ describe('useGetIssues', () => {
{ wrapper: appMockRender.AppWrapper }
);
await waitFor(() => result.current.isError);
expect(addError).toHaveBeenCalled();
await waitFor(() => {
expect(result.current.isError).toBe(true);
expect(addError).toHaveBeenCalled();
});
});
it('calls addError when the getIssues api returns successfully but contains an error', async () => {
@ -100,7 +102,7 @@ describe('useGetIssues', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useGetIssues({
http,
@ -110,8 +112,9 @@ describe('useGetIssues', () => {
{ wrapper: appMockRender.AppWrapper }
);
await waitFor(() => result.current.isSuccess);
expect(addError).toHaveBeenCalled();
await waitFor(() => {
expect(result.current.isSuccess).toBe(true);
expect(addError).toHaveBeenCalled();
});
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useKibana, useToasts } from '../../../common/lib/kibana';
import { connector } from '../mock';
@ -30,7 +30,7 @@ describe('useGetIncidentTypes', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'getIncidentTypes');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useGetIncidentTypes({
http,
@ -70,7 +70,7 @@ describe('useGetIncidentTypes', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { waitFor } = renderHook(
renderHook(
() =>
useGetIncidentTypes({
http,
@ -95,7 +95,7 @@ describe('useGetIncidentTypes', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { waitFor } = renderHook(
renderHook(
() =>
useGetIncidentTypes({
http,

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useKibana, useToasts } from '../../../common/lib/kibana';
import { connector } from '../mock';
@ -30,7 +30,7 @@ describe('useGetSeverity', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'getSeverity');
const { result, waitFor } = renderHook(
const { result } = renderHook(
() =>
useGetSeverity({
http,
@ -70,7 +70,7 @@ describe('useGetSeverity', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { waitFor } = renderHook(
renderHook(
() =>
useGetSeverity({
http,
@ -95,7 +95,7 @@ describe('useGetSeverity', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { waitFor } = renderHook(
renderHook(
() =>
useGetSeverity({
http,

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useKibana, useToasts } from '../../../common/lib/kibana';
import type { ActionConnector } from '../../../../common/types/domain';
@ -47,7 +47,7 @@ describe('useGetChoices', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'getChoices');
const { waitFor } = renderHook(
renderHook(
() =>
useGetChoices({
http,
@ -92,7 +92,7 @@ describe('useGetChoices', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { waitFor } = renderHook(
renderHook(
() =>
useGetChoices({
http,
@ -118,7 +118,7 @@ describe('useGetChoices', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess: jest.fn(), addError });
const { waitFor } = renderHook(
renderHook(
() =>
useGetChoices({
http,

View file

@ -6,7 +6,7 @@
*/
import { alertComment } from '../../../containers/mock';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import type { FC, PropsWithChildren } from 'react';
import React from 'react';
import { CasesContext } from '../../cases_context';
@ -47,12 +47,11 @@ describe('use cases add to new case flyout hook', () => {
});
it('should throw if called outside of a cases context', () => {
const { result } = renderHook(() => {
useCasesAddToNewCaseFlyout();
});
expect(result.error?.message).toContain(
'useCasesContext must be used within a CasesProvider and have a defined value'
);
expect(() =>
renderHook(() => {
useCasesAddToNewCaseFlyout();
})
).toThrow(/useCasesContext must be used within a CasesProvider and have a defined value/);
});
it('should dispatch the open action when invoked without attachments', () => {

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import type { AppMockRenderer } from '../../common/mock';
import { createAppMockRenderer } from '../../common/mock';
import { useCancelCreationAction } from './use_cancel_creation_action';

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useFilePreview } from './use_file_preview';

View file

@ -9,7 +9,7 @@ import type { FilesTableColumnsProps } from './use_files_table_columns';
import { useFilesTableColumns } from './use_files_table_columns';
import type { AppMockRenderer } from '../../common/mock';
import { createAppMockRenderer } from '../../common/mock';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { basicCase } from '../../containers/mock';
describe('useFilesTableColumns', () => {

View file

@ -5,11 +5,9 @@
* 2.0.
*/
import { renderHook, act } from '@testing-library/react-hooks';
import { waitFor, renderHook, act } from '@testing-library/react';
import type { FieldHook } from '@kbn/es-ui-shared-plugin/static/forms/hook_form_lib';
import type { SessionStorageType } from './use_markdown_session_storage';
import { useMarkdownSessionStorage } from './use_markdown_session_storage';
import { waitForComponentToUpdate } from '../../common/test_utils';
describe('useMarkdownSessionStorage', () => {
const field = {
@ -45,7 +43,7 @@ describe('useMarkdownSessionStorage', () => {
});
it('should return hasConflicts as false', async () => {
const { result, waitFor } = renderHook(() =>
const { result } = renderHook(() =>
useMarkdownSessionStorage({ field, sessionKey, initialValue })
);
@ -55,7 +53,7 @@ describe('useMarkdownSessionStorage', () => {
});
it('should return hasConflicts as false when sessionKey is empty', async () => {
const { result, waitFor } = renderHook(() =>
const { result } = renderHook(() =>
useMarkdownSessionStorage({ field, sessionKey: '', initialValue })
);
@ -66,7 +64,7 @@ describe('useMarkdownSessionStorage', () => {
});
it('should update the session value with field value when it is first render', async () => {
const { waitFor } = renderHook<SessionStorageType, { hasConflicts: boolean }>(
renderHook(
(props) => {
return useMarkdownSessionStorage(props);
},
@ -86,7 +84,7 @@ describe('useMarkdownSessionStorage', () => {
it('should set session storage when field has value and session key is not created yet', async () => {
const specialCharsValue = '!{tooltip[Hello again](This is tooltip!)}';
const { waitFor, result } = renderHook<SessionStorageType, { hasConflicts: boolean }>(
const { result } = renderHook(
(props) => {
return useMarkdownSessionStorage(props);
},
@ -101,8 +99,6 @@ describe('useMarkdownSessionStorage', () => {
jest.advanceTimersByTime(1000);
});
await waitForComponentToUpdate();
await waitFor(() => {
expect(result.current.hasConflicts).toBe(false);
expect(sessionStorage.getItem(sessionKey)).toBe(specialCharsValue);
@ -110,7 +106,7 @@ describe('useMarkdownSessionStorage', () => {
});
it('should update session value ', async () => {
const { result, rerender, waitFor } = renderHook<SessionStorageType, { hasConflicts: boolean }>(
const { result, rerender } = renderHook(
(props) => {
return useMarkdownSessionStorage(props);
},
@ -129,8 +125,6 @@ describe('useMarkdownSessionStorage', () => {
jest.advanceTimersByTime(1000);
});
await waitForComponentToUpdate();
await waitFor(() => {
expect(result.current.hasConflicts).toBe(false);
expect(sessionStorage.getItem(sessionKey)).toBe('new value');
@ -138,7 +132,7 @@ describe('useMarkdownSessionStorage', () => {
});
it('should return has conflict true', async () => {
const { result, rerender, waitFor } = renderHook<SessionStorageType, { hasConflicts: boolean }>(
const { result, rerender } = renderHook(
(props) => {
return useMarkdownSessionStorage(props);
},
@ -162,7 +156,7 @@ describe('useMarkdownSessionStorage', () => {
});
it('should set field value if session already exists and it is a first render', async () => {
const { waitFor, result } = renderHook<SessionStorageType, { hasConflicts: boolean }>(
const { result } = renderHook(
(props) => {
return useMarkdownSessionStorage(props);
},
@ -171,8 +165,6 @@ describe('useMarkdownSessionStorage', () => {
}
);
await waitForComponentToUpdate();
await waitFor(() => {
expect(field.setValue).toHaveBeenCalled();
});
@ -181,8 +173,6 @@ describe('useMarkdownSessionStorage', () => {
jest.advanceTimersByTime(1000);
});
await waitForComponentToUpdate();
await waitFor(() => {
expect(result.current.hasConflicts).toBe(false);
expect(field.value).toBe(sessionStorage.getItem(sessionKey));
@ -190,10 +180,7 @@ describe('useMarkdownSessionStorage', () => {
});
it('should update existing session key if field value changed', async () => {
const { waitFor, rerender, result } = renderHook<
SessionStorageType,
{ hasConflicts: boolean }
>(
const { rerender, result } = renderHook(
(props) => {
return useMarkdownSessionStorage(props);
},
@ -202,8 +189,6 @@ describe('useMarkdownSessionStorage', () => {
}
);
await waitForComponentToUpdate();
await waitFor(() => {
expect(field.setValue).toHaveBeenCalled();
});
@ -218,8 +203,6 @@ describe('useMarkdownSessionStorage', () => {
jest.advanceTimersByTime(1000);
});
await waitForComponentToUpdate();
await waitFor(() => {
expect(result.current.hasConflicts).toBe(false);
expect(sessionStorage.getItem(sessionKey)).toBe('new value');

View file

@ -7,7 +7,7 @@
import type { ReactNode } from 'react';
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { TestProviders } from '../../common/mock';
import { useCasesBreadcrumbs, useCasesTitleBreadcrumbs } from '.';
import { CasesDeepLinkId } from '../../common/navigation';

View file

@ -6,10 +6,10 @@
*/
import React from 'react';
import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { useKibana } from '../../common/lib/kibana';
import type { UseCreateCaseModalProps, UseCreateCaseModalReturnedValues } from '.';
import { useCreateCaseModal } from '.';
import { TestProviders } from '../../common/mock';
@ -27,10 +27,7 @@ describe('useCreateCaseModal', () => {
});
it('init', async () => {
const { result } = renderHook<
React.PropsWithChildren<UseCreateCaseModalProps>,
UseCreateCaseModalReturnedValues
>(() => useCreateCaseModal({ onCaseCreated }), {
const { result } = renderHook(() => useCreateCaseModal({ onCaseCreated }), {
wrapper: ({ children }) => <TestProviders>{children}</TestProviders>,
});
@ -38,10 +35,7 @@ describe('useCreateCaseModal', () => {
});
it('opens the modal', async () => {
const { result } = renderHook<
React.PropsWithChildren<UseCreateCaseModalProps>,
UseCreateCaseModalReturnedValues
>(() => useCreateCaseModal({ onCaseCreated }), {
const { result } = renderHook(() => useCreateCaseModal({ onCaseCreated }), {
wrapper: ({ children }) => <TestProviders>{children}</TestProviders>,
});
@ -53,10 +47,7 @@ describe('useCreateCaseModal', () => {
});
it('closes the modal', async () => {
const { result } = renderHook<
React.PropsWithChildren<UseCreateCaseModalProps>,
UseCreateCaseModalReturnedValues
>(() => useCreateCaseModal({ onCaseCreated }), {
const { result } = renderHook(() => useCreateCaseModal({ onCaseCreated }), {
wrapper: ({ children }) => <TestProviders>{children}</TestProviders>,
});
@ -69,10 +60,7 @@ describe('useCreateCaseModal', () => {
});
it('returns a memoized value', async () => {
const { result, rerender } = renderHook<
React.PropsWithChildren<UseCreateCaseModalProps>,
UseCreateCaseModalReturnedValues
>(() => useCreateCaseModal({ onCaseCreated }), {
const { result, rerender } = renderHook(() => useCreateCaseModal({ onCaseCreated }), {
wrapper: ({ children }) => <TestProviders>{children}</TestProviders>,
});
@ -84,10 +72,7 @@ describe('useCreateCaseModal', () => {
});
it('closes the modal when creating a case', async () => {
const { result } = renderHook<
React.PropsWithChildren<UseCreateCaseModalProps>,
UseCreateCaseModalReturnedValues
>(() => useCreateCaseModal({ onCaseCreated }), {
const { result } = renderHook(() => useCreateCaseModal({ onCaseCreated }), {
wrapper: ({ children }) => <TestProviders>{children}</TestProviders>,
});

View file

@ -6,9 +6,8 @@
*/
import React from 'react';
import { renderHook, act } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import type { ReturnUsePushToService, UsePushToService } from '.';
import { usePushToService } from '.';
import { noPushCasesPermissions, readCasesPermissions, TestProviders } from '../../common/mock';
import { usePostPushToService } from '../../containers/use_post_push_to_service';
@ -67,10 +66,7 @@ describe('usePushToService', () => {
});
it('calls pushCaseToExternalService with correct arguments', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
});
@ -93,10 +89,7 @@ describe('usePushToService', () => {
},
}));
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
});
@ -115,10 +108,7 @@ describe('usePushToService', () => {
},
}));
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
});
@ -129,10 +119,7 @@ describe('usePushToService', () => {
});
it('Displays message when user has select none as connector', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -155,10 +142,7 @@ describe('usePushToService', () => {
});
it('Displays message when connector is deleted', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -182,10 +166,7 @@ describe('usePushToService', () => {
});
it('should not call pushCaseToExternalService when the selected connector is none', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -209,10 +190,7 @@ describe('usePushToService', () => {
});
it('refresh case view page after push', async () => {
const { result, waitFor } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
});
@ -227,10 +205,7 @@ describe('usePushToService', () => {
describe('user does not have write or push permissions', () => {
it('returns correct information about push permissions', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => (
<TestProviders permissions={noPushCasesPermissions()}> {children}</TestProviders>
),
@ -248,10 +223,7 @@ describe('usePushToService', () => {
},
}));
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => (
<TestProviders permissions={readCasesPermissions()}> {children}</TestProviders>
),
@ -270,10 +242,7 @@ describe('usePushToService', () => {
},
}));
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => (
<TestProviders permissions={readCasesPermissions()}> {children}</TestProviders>
),
@ -284,10 +253,7 @@ describe('usePushToService', () => {
});
it('does not display a message when user does not have any connector configured', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -310,10 +276,7 @@ describe('usePushToService', () => {
});
it('does not display a message when user does have a connector but is configured to none', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -336,10 +299,7 @@ describe('usePushToService', () => {
});
it('does not display a message when connector is deleted', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -363,10 +323,7 @@ describe('usePushToService', () => {
});
it('does not display a message when case is closed', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -386,10 +343,7 @@ describe('usePushToService', () => {
describe('returned values', () => {
it('initial', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
});
@ -408,10 +362,7 @@ describe('usePushToService', () => {
it('isLoading is true when usePostPushToService is loading', async () => {
usePostPushToServiceMock.mockReturnValue({ ...mockPostPush, isLoading: true });
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
});
@ -424,10 +375,7 @@ describe('usePushToService', () => {
data: actionLicense,
});
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
});
@ -435,21 +383,18 @@ describe('usePushToService', () => {
});
it('hasErrorMessages=true if there are error messages', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService({ ...defaultArgs, isValidConnector: false }), {
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
});
const { result } = renderHook(
() => usePushToService({ ...defaultArgs, isValidConnector: false }),
{
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
}
);
expect(result.current.hasErrorMessages).toBe(true);
});
it('needsToBePushed=true if the connector needs to be pushed', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -473,10 +418,7 @@ describe('usePushToService', () => {
});
it('needsToBePushed=false if the connector does not exist', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -497,10 +439,7 @@ describe('usePushToService', () => {
});
it('hasBeenPushed=false if the connector has been pushed', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -524,10 +463,7 @@ describe('usePushToService', () => {
});
it('hasBeenPushed=false if the connector does not exist', async () => {
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(
const { result } = renderHook(
() =>
usePushToService({
...defaultArgs,
@ -553,10 +489,7 @@ describe('usePushToService', () => {
data: actionLicense,
});
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => (
<TestProviders permissions={noPushCasesPermissions()}> {children}</TestProviders>
),
@ -574,10 +507,7 @@ describe('usePushToService', () => {
},
}));
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
});
@ -590,10 +520,7 @@ describe('usePushToService', () => {
data: undefined,
}));
const { result } = renderHook<
React.PropsWithChildren<UsePushToService>,
ReturnUsePushToService
>(() => usePushToService(defaultArgs), {
const { result } = renderHook(() => usePushToService(defaultArgs), {
wrapper: ({ children }) => <TestProviders> {children}</TestProviders>,
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import type { AppMockRenderer } from '../../../common/mock';
import { createAppMockRenderer } from '../../../common/mock';
import { useDeletePropertyAction } from './use_delete_property_action';

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { renderHook } from '@testing-library/react';
import { useLastPage } from './use_last_page';
import type { UserActivityParams } from '../user_actions_activity_bar/types';

View file

@ -7,7 +7,7 @@
import type { FC, PropsWithChildren } from 'react';
import React from 'react';
import { renderHook, act } from '@testing-library/react-hooks';
import { renderHook, act } from '@testing-library/react';
import { basicCase } from '../../containers/mock';
import { useUpdateComment } from '../../containers/use_update_comment';

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useLastPageUserActions } from './use_user_actions_last_page';
import type { UserActivityParams } from '../user_actions_activity_bar/types';
@ -32,7 +32,7 @@ describe('useLastPageUserActions', () => {
});
it('renders correctly', async () => {
const { result, waitFor } = renderHook(() =>
const { result } = renderHook(() =>
useLastPageUserActions({
lastPage: 5,
userActivityQueryParams,
@ -79,7 +79,7 @@ describe('useLastPageUserActions', () => {
it('returns loading state correctly', async () => {
useFindCaseUserActionsMock.mockReturnValue({ isLoading: true });
const { result, waitFor } = renderHook(() =>
const { result } = renderHook(() =>
useLastPageUserActions({
lastPage: 2,
userActivityQueryParams,
@ -108,7 +108,7 @@ describe('useLastPageUserActions', () => {
it('returns empty array when data is undefined', async () => {
useFindCaseUserActionsMock.mockReturnValue({ isLoading: false, data: undefined });
const { result, waitFor } = renderHook(() =>
const { result } = renderHook(() =>
useLastPageUserActions({
lastPage: 2,
userActivityQueryParams,

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useUserActionsPagination } from './use_user_actions_pagination';
import type { UserActivityParams } from '../user_actions_activity_bar/types';
@ -32,7 +32,7 @@ describe('useUserActionsPagination', () => {
});
it('renders expandable option correctly when user actions are more than 10', async () => {
const { result, waitFor } = renderHook(() =>
const { result } = renderHook(() =>
useUserActionsPagination({
userActivityQueryParams,
caseId: basicCase.id,
@ -62,7 +62,7 @@ describe('useUserActionsPagination', () => {
});
it('renders less than 10 user actions correctly', async () => {
const { result, waitFor } = renderHook(() =>
const { result } = renderHook(() =>
useUserActionsPagination({
userActivityQueryParams,
caseId: basicCase.id,
@ -92,7 +92,7 @@ describe('useUserActionsPagination', () => {
it('returns loading state correctly', async () => {
useInfiniteFindCaseUserActionsMock.mockReturnValue({ isLoading: true });
const { result, waitFor } = renderHook(() =>
const { result } = renderHook(() =>
useUserActionsPagination({
userActivityQueryParams,
caseId: basicCase.id,
@ -124,7 +124,7 @@ describe('useUserActionsPagination', () => {
it('returns empty array when data is undefined', async () => {
useInfiniteFindCaseUserActionsMock.mockReturnValue({ isLoading: false, data: undefined });
const { result, waitFor } = renderHook(() =>
const { result } = renderHook(() =>
useUserActionsPagination({
userActivityQueryParams,
caseId: basicCase.id,
@ -161,7 +161,7 @@ describe('useUserActionsPagination', () => {
},
});
const { result, waitFor } = renderHook(() =>
const { result } = renderHook(() =>
useUserActionsPagination({
userActivityQueryParams,
caseId: basicCase.id,

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import * as api from './api';
import type { AppMockRenderer } from '../../common/mock';
import { createAppMockRenderer } from '../../common/mock';
@ -43,10 +43,10 @@ describe('useActionTypes', () => {
(useToasts as jest.Mock).mockReturnValue({ addError: addErrorMock });
const { waitForNextUpdate } = renderHook(() => useGetActionTypes(), {
renderHook(() => useGetActionTypes(), {
wrapper: appMockRenderer.AppWrapper,
});
await waitForNextUpdate({ timeout: 2000 });
expect(addErrorMock).toHaveBeenCalled();
await waitFor(() => expect(addErrorMock).toHaveBeenCalled());
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useGetAllCaseConfigurations } from './use_get_all_case_configurations';
import * as api from './api';
import type { AppMockRenderer } from '../../common/mock';
@ -32,18 +32,11 @@ describe('Use get all case configurations hook', () => {
{ id: 'my-configuration-3', owner: '3' },
]);
const { result, waitForNextUpdate } = renderHook(() => useGetAllCaseConfigurations(), {
const { result } = renderHook(() => useGetAllCaseConfigurations(), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
/**
* Ensures that the initial data is returned
* before fetching
*/
// @ts-expect-error: data is defined
expect(result.all[0].data).toEqual([
expect(result.current.data).toEqual([
{
closureType: 'close-by-user',
connector: { fields: null, id: 'none', name: 'none', type: '.none' },
@ -56,43 +49,36 @@ describe('Use get all case configurations hook', () => {
},
]);
/**
* The response after fetching
*/
// @ts-expect-error: data is defined
expect(result.all[1].data).toEqual([
{ id: 'my-configuration-1', owner: '1' },
{ id: 'my-configuration-2', owner: '2' },
{ id: 'my-configuration-3', owner: '3' },
]);
await waitFor(() =>
expect(result.current.data).toEqual([
{ id: 'my-configuration-1', owner: '1' },
{ id: 'my-configuration-2', owner: '2' },
{ id: 'my-configuration-3', owner: '3' },
])
);
});
it('returns the initial configuration if none is available', async () => {
const spy = jest.spyOn(api, 'getCaseConfigure');
spy.mockResolvedValue([]);
const { result, waitForNextUpdate } = renderHook(() => useGetAllCaseConfigurations(), {
const { result } = renderHook(() => useGetAllCaseConfigurations(), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
/**
* Ensures that the initial data is returned
* before fetching
*/
// @ts-expect-error: data is defined
expect(result.all[0].data).toEqual([
{
closureType: 'close-by-user',
connector: { fields: null, id: 'none', name: 'none', type: '.none' },
customFields: [],
templates: [],
id: '',
mappings: [],
version: '',
owner: '',
},
]);
await waitFor(() =>
expect(result.current.data).toEqual([
{
closureType: 'close-by-user',
connector: { fields: null, id: 'none', name: 'none', type: '.none' },
customFields: [],
templates: [],
id: '',
mappings: [],
version: '',
owner: '',
},
])
);
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useGetCaseConfiguration } from './use_get_case_configuration';
import * as api from './api';
import type { AppMockRenderer } from '../../common/mock';
@ -35,16 +35,14 @@ describe('Use get case configuration hook', () => {
targetConfiguration,
]);
const { result, waitForNextUpdate } = renderHook(() => useGetCaseConfiguration(), {
const { result } = renderHook(() => useGetCaseConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
/**
* The response after fetching
*/
expect(result.current.data).toEqual(targetConfiguration);
await waitFor(() => expect(result.current.data).toEqual(targetConfiguration));
});
it('returns the initial configuration if none matches the owner', async () => {
@ -59,16 +57,14 @@ describe('Use get case configuration hook', () => {
{ ...initialConfiguration, id: 'my-new-configuration-2', owner: 'bar' },
]);
const { result, waitForNextUpdate } = renderHook(() => useGetCaseConfiguration(), {
const { result } = renderHook(() => useGetCaseConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
/**
* The response after fetching
*/
expect(result.current.data).toEqual(initialConfiguration);
await waitFor(() => expect(result.current.data).toEqual(initialConfiguration));
});
it('returns the initial configuration if none exists', async () => {
@ -76,16 +72,14 @@ describe('Use get case configuration hook', () => {
spy.mockResolvedValue([]);
const { result, waitForNextUpdate } = renderHook(() => useGetCaseConfiguration(), {
const { result } = renderHook(() => useGetCaseConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
/**
* The response after fetching
*/
expect(result.current.data).toEqual(initialConfiguration);
await waitFor(() => expect(result.current.data).toEqual(initialConfiguration));
});
it('returns the initial configuration if the owner is undefined', async () => {
@ -94,15 +88,13 @@ describe('Use get case configuration hook', () => {
spy.mockResolvedValue([]);
const { result, waitForNextUpdate } = renderHook(() => useGetCaseConfiguration(), {
const { result } = renderHook(() => useGetCaseConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
/**
* The response after fetching
*/
expect(result.current.data).toEqual(initialConfiguration);
await waitFor(() => expect(result.current.data).toEqual(initialConfiguration));
});
});

View file

@ -5,10 +5,9 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { useGetCaseConfigurationsQuery } from './use_get_case_configurations_query';
import * as api from './api';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import { useToasts } from '../../common/lib/kibana';
import type { AppMockRenderer } from '../../common/mock';
import { createAppMockRenderer } from '../../common/mock';

View file

@ -6,7 +6,7 @@
*/
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import * as api from './api';
import { noConnectorsCasePermission, TestProviders } from '../../common/mock';
import { useApplicationCapabilities, useToasts } from '../../common/lib/kibana';
@ -26,15 +26,13 @@ describe('useConnectors', () => {
it('fetches connectors', async () => {
const spy = jest.spyOn(api, 'getSupportedActionConnectors');
const { waitForNextUpdate } = renderHook(() => useGetSupportedActionConnectors(), {
renderHook(() => useGetSupportedActionConnectors(), {
wrapper: ({ children }: React.PropsWithChildren<{}>) => (
<TestProviders>{children}</TestProviders>
),
});
await waitForNextUpdate();
expect(spy).toHaveBeenCalledWith({ signal: expect.any(AbortSignal) });
await waitFor(() => expect(spy).toHaveBeenCalledWith({ signal: expect.any(AbortSignal) }));
});
it('shows a toast error when the API returns error', async () => {
@ -46,45 +44,44 @@ describe('useConnectors', () => {
throw new Error('Something went wrong');
});
const { waitForNextUpdate } = renderHook(() => useGetSupportedActionConnectors(), {
renderHook(() => useGetSupportedActionConnectors(), {
wrapper: ({ children }: React.PropsWithChildren<{}>) => (
<TestProviders>{children}</TestProviders>
),
});
await waitForNextUpdate();
expect(addError).toHaveBeenCalled();
await waitFor(() => expect(addError).toHaveBeenCalled());
});
it('does not fetch connectors when the user does not has access to actions', async () => {
const spyOnFetchConnectors = jest.spyOn(api, 'getSupportedActionConnectors');
useApplicationCapabilitiesMock().actions = { crud: false, read: false };
const { result, waitForNextUpdate } = renderHook(() => useGetSupportedActionConnectors(), {
const { result } = renderHook(() => useGetSupportedActionConnectors(), {
wrapper: ({ children }: React.PropsWithChildren<{}>) => (
<TestProviders>{children}</TestProviders>
),
});
await waitForNextUpdate();
expect(spyOnFetchConnectors).not.toHaveBeenCalled();
expect(result.current.data).toEqual([]);
await waitFor(() => {
expect(spyOnFetchConnectors).not.toHaveBeenCalled();
expect(result.current.data).toEqual([]);
});
});
it('does not fetch connectors when the user does not has access to connectors', async () => {
const spyOnFetchConnectors = jest.spyOn(api, 'getSupportedActionConnectors');
useApplicationCapabilitiesMock().actions = { crud: true, read: true };
const { result, waitForNextUpdate } = renderHook(() => useGetSupportedActionConnectors(), {
const { result } = renderHook(() => useGetSupportedActionConnectors(), {
wrapper: ({ children }: React.PropsWithChildren<{}>) => (
<TestProviders permissions={noConnectorsCasePermission()}>{children}</TestProviders>
),
});
await waitForNextUpdate();
expect(spyOnFetchConnectors).not.toHaveBeenCalled();
expect(result.current.data).toEqual([]);
await waitFor(() => {
expect(spyOnFetchConnectors).not.toHaveBeenCalled();
expect(result.current.data).toEqual([]);
});
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook, act } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { usePersistConfiguration } from './use_persist_configuration';
import * as api from './api';
@ -55,7 +55,7 @@ describe('usePersistConfiguration', () => {
const spyPost = jest.spyOn(api, 'postCaseConfigure');
const spyPatch = jest.spyOn(api, 'patchCaseConfigure');
const { waitFor, result } = renderHook(() => usePersistConfiguration(), {
const { result } = renderHook(() => usePersistConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
@ -80,7 +80,7 @@ describe('usePersistConfiguration', () => {
const spyPost = jest.spyOn(api, 'postCaseConfigure');
const spyPatch = jest.spyOn(api, 'patchCaseConfigure');
const { waitFor, result } = renderHook(() => usePersistConfiguration(), {
const { result } = renderHook(() => usePersistConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
@ -104,7 +104,7 @@ describe('usePersistConfiguration', () => {
it('calls postCaseConfigure with correct data', async () => {
const spyPost = jest.spyOn(api, 'postCaseConfigure');
const { waitFor, result } = renderHook(() => usePersistConfiguration(), {
const { result } = renderHook(() => usePersistConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
@ -133,7 +133,7 @@ describe('usePersistConfiguration', () => {
const spyPost = jest.spyOn(api, 'postCaseConfigure');
const spyPatch = jest.spyOn(api, 'patchCaseConfigure');
const { waitFor, result } = renderHook(() => usePersistConfiguration(), {
const { result } = renderHook(() => usePersistConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
@ -157,7 +157,7 @@ describe('usePersistConfiguration', () => {
it('calls patchCaseConfigure with correct data', async () => {
const spyPatch = jest.spyOn(api, 'patchCaseConfigure');
const { waitFor, result } = renderHook(() => usePersistConfiguration(), {
const { result } = renderHook(() => usePersistConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
@ -184,7 +184,7 @@ describe('usePersistConfiguration', () => {
it('invalidates the queries correctly', async () => {
const queryClientSpy = jest.spyOn(appMockRender.queryClient, 'invalidateQueries');
const { waitFor, result } = renderHook(() => usePersistConfiguration(), {
const { result } = renderHook(() => usePersistConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
@ -198,7 +198,7 @@ describe('usePersistConfiguration', () => {
});
it('shows the success toaster', async () => {
const { waitFor, result } = renderHook(() => usePersistConfiguration(), {
const { result } = renderHook(() => usePersistConfiguration(), {
wrapper: appMockRender.AppWrapper,
});
@ -216,7 +216,7 @@ describe('usePersistConfiguration', () => {
.spyOn(api, 'postCaseConfigure')
.mockRejectedValue(new Error('useCreateAttachments: Test error'));
const { waitFor, result } = renderHook(() => usePersistConfiguration(), {
const { result } = renderHook(() => usePersistConfiguration(), {
wrapper: appMockRender.AppWrapper,
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook, act } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { useUpdateCases } from './use_bulk_update_case';
import { allCases } from './mock';
import { useToasts } from '../common/lib/kibana';
@ -32,7 +32,7 @@ describe('useUpdateCases', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'updateCases');
const { waitForNextUpdate, result } = renderHook(() => useUpdateCases(), {
const { result } = renderHook(() => useUpdateCases(), {
wrapper: appMockRender.AppWrapper,
});
@ -40,14 +40,12 @@ describe('useUpdateCases', () => {
result.current.mutate({ cases: allCases.cases, successToasterTitle: 'Success title' });
});
await waitForNextUpdate();
expect(spy).toHaveBeenCalledWith({ cases: allCases.cases });
await waitFor(() => expect(spy).toHaveBeenCalledWith({ cases: allCases.cases }));
});
it('invalidates the queries correctly', async () => {
const queryClientSpy = jest.spyOn(appMockRender.queryClient, 'invalidateQueries');
const { waitForNextUpdate, result } = renderHook(() => useUpdateCases(), {
const { result } = renderHook(() => useUpdateCases(), {
wrapper: appMockRender.AppWrapper,
});
@ -55,15 +53,15 @@ describe('useUpdateCases', () => {
result.current.mutate({ cases: allCases.cases, successToasterTitle: 'Success title' });
});
await waitForNextUpdate();
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.casesList());
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.tags());
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.userProfiles());
await waitFor(() => {
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.casesList());
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.tags());
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.userProfiles());
});
});
it('shows a success toaster', async () => {
const { waitForNextUpdate, result } = renderHook(() => useUpdateCases(), {
const { result } = renderHook(() => useUpdateCases(), {
wrapper: appMockRender.AppWrapper,
});
@ -71,18 +69,18 @@ describe('useUpdateCases', () => {
result.current.mutate({ cases: allCases.cases, successToasterTitle: 'Success title' });
});
await waitForNextUpdate();
expect(addSuccess).toHaveBeenCalledWith({
title: 'Success title',
className: 'eui-textBreakWord',
});
await waitFor(() =>
expect(addSuccess).toHaveBeenCalledWith({
title: 'Success title',
className: 'eui-textBreakWord',
})
);
});
it('shows a toast error when the api return an error', async () => {
jest.spyOn(api, 'updateCases').mockRejectedValue(new Error('useUpdateCases: Test error'));
const { waitForNextUpdate, result } = renderHook(() => useUpdateCases(), {
const { result } = renderHook(() => useUpdateCases(), {
wrapper: appMockRender.AppWrapper,
});
@ -90,8 +88,6 @@ describe('useUpdateCases', () => {
result.current.mutate({ cases: allCases.cases, successToasterTitle: 'Success title' });
});
await waitForNextUpdate();
expect(addError).toHaveBeenCalled();
await waitFor(() => expect(addError).toHaveBeenCalled());
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook, act } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { AttachmentType } from '../../common/types/domain';
import { SECURITY_SOLUTION_OWNER } from '../../common/constants';
@ -58,7 +58,7 @@ describe('useCreateAttachments', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'createAttachments');
const { waitForNextUpdate, result } = renderHook(() => useCreateAttachments(), {
const { result } = renderHook(() => useCreateAttachments(), {
wrapper: appMockRender.AppWrapper,
});
@ -66,13 +66,16 @@ describe('useCreateAttachments', () => {
result.current.mutate(request);
});
await waitForNextUpdate();
expect(spy).toHaveBeenCalledWith({ attachments: attachmentsWithOwner, caseId: request.caseId });
await waitFor(() =>
expect(spy).toHaveBeenCalledWith({
attachments: attachmentsWithOwner,
caseId: request.caseId,
})
);
});
it('does not show a success toaster', async () => {
const { waitForNextUpdate, result } = renderHook(() => useCreateAttachments(), {
const { result } = renderHook(() => useCreateAttachments(), {
wrapper: appMockRender.AppWrapper,
});
@ -80,9 +83,7 @@ describe('useCreateAttachments', () => {
result.current.mutate(request);
});
await waitForNextUpdate();
expect(addSuccess).not.toHaveBeenCalled();
await waitFor(() => expect(addSuccess).not.toHaveBeenCalled());
});
it('shows a toast error when the api return an error', async () => {
@ -90,7 +91,7 @@ describe('useCreateAttachments', () => {
.spyOn(api, 'createAttachments')
.mockRejectedValue(new Error('useCreateAttachments: Test error'));
const { waitForNextUpdate, result } = renderHook(() => useCreateAttachments(), {
const { result } = renderHook(() => useCreateAttachments(), {
wrapper: appMockRender.AppWrapper,
});
@ -98,8 +99,6 @@ describe('useCreateAttachments', () => {
result.current.mutate(request);
});
await waitForNextUpdate();
expect(addError).toHaveBeenCalled();
await waitFor(() => expect(addError).toHaveBeenCalled());
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook, act } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { useDeleteCases } from './use_delete_cases';
import * as api from './api';
@ -32,7 +32,7 @@ describe('useDeleteCases', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'deleteCases');
const { waitForNextUpdate, result } = renderHook(() => useDeleteCases(), {
const { result } = renderHook(() => useDeleteCases(), {
wrapper: appMockRender.AppWrapper,
});
@ -40,14 +40,12 @@ describe('useDeleteCases', () => {
result.current.mutate({ caseIds: ['1', '2'], successToasterTitle: 'Success title' });
});
await waitForNextUpdate();
expect(spy).toHaveBeenCalledWith({ caseIds: ['1', '2'] });
await waitFor(() => expect(spy).toHaveBeenCalledWith({ caseIds: ['1', '2'] }));
});
it('invalidates the queries correctly', async () => {
const queryClientSpy = jest.spyOn(appMockRender.queryClient, 'invalidateQueries');
const { waitForNextUpdate, result } = renderHook(() => useDeleteCases(), {
const { result } = renderHook(() => useDeleteCases(), {
wrapper: appMockRender.AppWrapper,
});
@ -55,15 +53,15 @@ describe('useDeleteCases', () => {
result.current.mutate({ caseIds: ['1', '2'], successToasterTitle: 'Success title' });
});
await waitForNextUpdate();
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.casesList());
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.tags());
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.userProfiles());
await waitFor(() => {
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.casesList());
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.tags());
expect(queryClientSpy).toHaveBeenCalledWith(casesQueriesKeys.userProfiles());
});
});
it('shows a success toaster', async () => {
const { waitForNextUpdate, result } = renderHook(() => useDeleteCases(), {
const { result } = renderHook(() => useDeleteCases(), {
wrapper: appMockRender.AppWrapper,
});
@ -71,18 +69,18 @@ describe('useDeleteCases', () => {
result.current.mutate({ caseIds: ['1', '2'], successToasterTitle: 'Success title' });
});
await waitForNextUpdate();
expect(addSuccess).toHaveBeenCalledWith({
title: 'Success title',
className: 'eui-textBreakWord',
});
await waitFor(() =>
expect(addSuccess).toHaveBeenCalledWith({
title: 'Success title',
className: 'eui-textBreakWord',
})
);
});
it('shows a toast error when the api return an error', async () => {
jest.spyOn(api, 'deleteCases').mockRejectedValue(new Error('useDeleteCases: Test error'));
const { waitForNextUpdate, result } = renderHook(() => useDeleteCases(), {
const { result } = renderHook(() => useDeleteCases(), {
wrapper: appMockRender.AppWrapper,
});
@ -90,8 +88,6 @@ describe('useDeleteCases', () => {
result.current.mutate({ caseIds: ['1', '2'], successToasterTitle: 'Success title' });
});
await waitForNextUpdate();
expect(addError).toHaveBeenCalled();
await waitFor(() => expect(addError).toHaveBeenCalled());
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import { useDeleteComment } from './use_delete_comment';
import * as api from './api';
import { basicCaseId } from './mock';
@ -45,7 +45,7 @@ describe('useDeleteComment', () => {
it('calls deleteComment with correct arguments - case', async () => {
const spyOnDeleteComment = jest.spyOn(api, 'deleteComment');
const { waitForNextUpdate, result } = renderHook(() => useDeleteComment(), {
const { result } = renderHook(() => useDeleteComment(), {
wrapper: appMockRender.AppWrapper,
});
@ -57,32 +57,16 @@ describe('useDeleteComment', () => {
});
});
await waitForNextUpdate();
expect(spyOnDeleteComment).toBeCalledWith({
caseId: basicCaseId,
commentId,
});
await waitFor(() =>
expect(spyOnDeleteComment).toBeCalledWith({
caseId: basicCaseId,
commentId,
})
);
});
it('refreshes the case page view after delete', async () => {
const { waitForNextUpdate, result } = renderHook(() => useDeleteComment(), {
wrapper: appMockRender.AppWrapper,
});
result.current.mutate({
caseId: basicCaseId,
commentId,
successToasterTitle,
});
await waitForNextUpdate();
expect(useRefreshCaseViewPage()).toBeCalled();
});
it('shows a success toaster correctly', async () => {
const { waitForNextUpdate, result } = renderHook(() => useDeleteComment(), {
const { result } = renderHook(() => useDeleteComment(), {
wrapper: appMockRender.AppWrapper,
});
@ -94,36 +78,54 @@ describe('useDeleteComment', () => {
});
});
await waitForNextUpdate();
await waitFor(() => expect(useRefreshCaseViewPage()).toBeCalled());
});
expect(addSuccess).toHaveBeenCalledWith({
title: 'Deleted',
className: 'eui-textBreakWord',
it('shows a success toaster correctly', async () => {
const { result } = renderHook(() => useDeleteComment(), {
wrapper: appMockRender.AppWrapper,
});
act(() => {
result.current.mutate({
caseId: basicCaseId,
commentId,
successToasterTitle,
});
});
await waitFor(() =>
expect(addSuccess).toHaveBeenCalledWith({
title: 'Deleted',
className: 'eui-textBreakWord',
})
);
});
it('sets isError when fails to delete a case', async () => {
const spyOnDeleteComment = jest.spyOn(api, 'deleteComment');
spyOnDeleteComment.mockRejectedValue(new Error('Error'));
const { waitForNextUpdate, result } = renderHook(() => useDeleteComment(), {
const { result } = renderHook(() => useDeleteComment(), {
wrapper: appMockRender.AppWrapper,
});
result.current.mutate({
caseId: basicCaseId,
commentId,
successToasterTitle,
act(() => {
result.current.mutate({
caseId: basicCaseId,
commentId,
successToasterTitle,
});
});
await waitForNextUpdate();
await waitFor(() => {
expect(spyOnDeleteComment).toBeCalledWith({
caseId: basicCaseId,
commentId,
});
expect(spyOnDeleteComment).toBeCalledWith({
caseId: basicCaseId,
commentId,
expect(addError).toHaveBeenCalled();
expect(result.current.isError).toBe(true);
});
expect(addError).toHaveBeenCalled();
expect(result.current.isError).toBe(true);
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { act, renderHook } from '@testing-library/react-hooks';
import { act, waitFor, renderHook } from '@testing-library/react';
import * as api from './api';
import { basicCaseId, basicFileMock } from './mock';
import { useRefreshCaseViewPage } from '../components/case_view/use_on_refresh_case_view_page';
@ -34,7 +34,7 @@ describe('useDeleteFileAttachment', () => {
it('calls deleteFileAttachment with correct arguments - case', async () => {
const spyOnDeleteFileAttachments = jest.spyOn(api, 'deleteFileAttachments');
const { waitForNextUpdate, result } = renderHook(() => useDeleteFileAttachment(), {
const { result } = renderHook(() => useDeleteFileAttachment(), {
wrapper: appMockRender.AppWrapper,
});
@ -45,16 +45,16 @@ describe('useDeleteFileAttachment', () => {
});
});
await waitForNextUpdate();
expect(spyOnDeleteFileAttachments).toHaveBeenCalledWith({
caseId: basicCaseId,
fileIds: [basicFileMock.id],
});
await waitFor(() =>
expect(spyOnDeleteFileAttachments).toHaveBeenCalledWith({
caseId: basicCaseId,
fileIds: [basicFileMock.id],
})
);
});
it('refreshes the case page view', async () => {
const { waitForNextUpdate, result } = renderHook(() => useDeleteFileAttachment(), {
const { result } = renderHook(() => useDeleteFileAttachment(), {
wrapper: appMockRender.AppWrapper,
});
@ -65,13 +65,11 @@ describe('useDeleteFileAttachment', () => {
})
);
await waitForNextUpdate();
expect(useRefreshCaseViewPage()).toBeCalled();
await waitFor(() => expect(useRefreshCaseViewPage()).toBeCalled());
});
it('shows a success toaster correctly', async () => {
const { waitForNextUpdate, result } = renderHook(() => useDeleteFileAttachment(), {
const { result } = renderHook(() => useDeleteFileAttachment(), {
wrapper: appMockRender.AppWrapper,
});
@ -82,19 +80,19 @@ describe('useDeleteFileAttachment', () => {
})
);
await waitForNextUpdate();
expect(addSuccess).toHaveBeenCalledWith({
title: 'File deleted successfully',
className: 'eui-textBreakWord',
});
await waitFor(() =>
expect(addSuccess).toHaveBeenCalledWith({
title: 'File deleted successfully',
className: 'eui-textBreakWord',
})
);
});
it('sets isError when fails to delete a file attachment', async () => {
const spyOnDeleteFileAttachments = jest.spyOn(api, 'deleteFileAttachments');
spyOnDeleteFileAttachments.mockRejectedValue(new Error('Error'));
const { waitForNextUpdate, result } = renderHook(() => useDeleteFileAttachment(), {
const { result } = renderHook(() => useDeleteFileAttachment(), {
wrapper: appMockRender.AppWrapper,
});
@ -105,7 +103,7 @@ describe('useDeleteFileAttachment', () => {
})
);
await waitForNextUpdate();
await waitFor(() => expect(result.current.isError).toBe(true));
expect(spyOnDeleteFileAttachments).toBeCalledWith({
caseId: basicCaseId,
@ -113,6 +111,5 @@ describe('useDeleteFileAttachment', () => {
});
expect(addError).toHaveBeenCalled();
expect(result.current.isError).toBe(true);
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useFindCaseUserActions } from './use_find_case_user_actions';
import type { CaseUserActionTypeWithAll } from '../../common/ui/types';
import { basicCase, findCaseUserActionsResponse } from './mock';
@ -43,33 +43,32 @@ describe('UseFindCaseUserActions', () => {
});
it('returns proper state on findCaseUserActions', async () => {
const { result, waitForNextUpdate } = renderHook(
() => useFindCaseUserActions(basicCase.id, params, isEnabled),
{ wrapper: appMockRender.AppWrapper }
);
const { result } = renderHook(() => useFindCaseUserActions(basicCase.id, params, isEnabled), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
expect(result.current).toEqual(
expect.objectContaining({
...initialData,
data: {
userActions: [...findCaseUserActionsResponse.userActions],
total: 30,
perPage: 10,
page: 1,
},
isError: false,
isLoading: false,
isFetching: false,
})
await waitFor(() =>
expect(result.current).toEqual(
expect.objectContaining({
...initialData,
data: {
userActions: [...findCaseUserActionsResponse.userActions],
total: 30,
perPage: 10,
page: 1,
},
isError: false,
isLoading: false,
isFetching: false,
})
)
);
});
it('calls the API with correct parameters', async () => {
const spy = jest.spyOn(api, 'findCaseUserActions').mockRejectedValue(initialData);
const { waitForNextUpdate } = renderHook(
renderHook(
() =>
useFindCaseUserActions(
basicCase.id,
@ -84,12 +83,12 @@ describe('UseFindCaseUserActions', () => {
{ wrapper: appMockRender.AppWrapper }
);
await waitForNextUpdate();
expect(spy).toHaveBeenCalledWith(
basicCase.id,
{ type: 'user', sortOrder: 'desc', page: 1, perPage: 5 },
expect.any(AbortSignal)
await waitFor(() =>
expect(spy).toHaveBeenCalledWith(
basicCase.id,
{ type: 'user', sortOrder: 'desc', page: 1, perPage: 5 },
expect.any(AbortSignal)
)
);
});
@ -120,20 +119,17 @@ describe('UseFindCaseUserActions', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addError });
const { waitForNextUpdate } = renderHook(
() => useFindCaseUserActions(basicCase.id, params, isEnabled),
{
wrapper: appMockRender.AppWrapper,
}
);
renderHook(() => useFindCaseUserActions(basicCase.id, params, isEnabled), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
expect(spy).toHaveBeenCalledWith(
basicCase.id,
{ type: filterActionType, sortOrder, page: 1, perPage: 10 },
expect.any(AbortSignal)
);
expect(addError).toHaveBeenCalled();
await waitFor(() => {
expect(spy).toHaveBeenCalledWith(
basicCase.id,
{ type: filterActionType, sortOrder, page: 1, perPage: 10 },
expect.any(AbortSignal)
);
expect(addError).toHaveBeenCalled();
});
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import * as api from './api';
import { useGetActionLicense } from './use_get_action_license';
import type { AppMockRenderer } from '../common/mock';
@ -25,12 +25,11 @@ describe('useGetActionLicense', () => {
it('calls getActionLicense with correct arguments', async () => {
const spyOnGetActionLicense = jest.spyOn(api, 'getActionLicense');
const { waitForNextUpdate } = renderHook(() => useGetActionLicense(), {
renderHook(() => useGetActionLicense(), {
wrapper: appMockRenderer.AppWrapper,
});
await waitForNextUpdate();
expect(spyOnGetActionLicense).toBeCalledWith(abortCtrl.signal);
await waitFor(() => expect(spyOnGetActionLicense).toBeCalledWith(abortCtrl.signal));
});
it('unhappy path', async () => {
@ -42,11 +41,9 @@ describe('useGetActionLicense', () => {
throw new Error('Something went wrong');
});
const { waitForNextUpdate } = renderHook(() => useGetActionLicense(), {
renderHook(() => useGetActionLicense(), {
wrapper: appMockRenderer.AppWrapper,
});
await waitForNextUpdate();
expect(addError).toHaveBeenCalled();
await waitFor(() => expect(addError).toHaveBeenCalled());
});
});

View file

@ -5,10 +5,9 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { useGetCase } from './use_get_case';
import * as api from './api';
import { waitFor } from '@testing-library/react';
import { waitFor, renderHook } from '@testing-library/react';
import type { FC, PropsWithChildren } from 'react';
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
@ -32,21 +31,21 @@ const wrapper: FC<PropsWithChildren<unknown>> = ({ children }) => {
describe.skip('Use get case hook', () => {
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'resolveCase');
const { waitForNextUpdate } = renderHook(() => useGetCase('case-1'), { wrapper });
await waitForNextUpdate();
expect(spy).toHaveBeenCalledWith({
caseId: 'case-1',
includeComments: true,
signal: expect.any(AbortSignal),
});
renderHook(() => useGetCase('case-1'), { wrapper });
await waitFor(() =>
expect(spy).toHaveBeenCalledWith({
caseId: 'case-1',
includeComments: true,
signal: expect.any(AbortSignal),
})
);
});
it('shows a toast error when the api return an error', async () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addError });
const spy = jest.spyOn(api, 'resolveCase').mockRejectedValue(new Error("C'est la vie"));
const { waitForNextUpdate } = renderHook(() => useGetCase('case-1'), { wrapper });
await waitForNextUpdate();
renderHook(() => useGetCase('case-1'), { wrapper });
await waitFor(() => {
expect(spy).toHaveBeenCalledWith({
caseId: 'case-1',

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import * as api from './api';
import type { AppMockRenderer } from '../common/mock';
import { createAppMockRenderer } from '../common/mock';
@ -30,7 +30,7 @@ describe('useGetCaseConnectors', () => {
it('calls getCaseConnectors with correct arguments', async () => {
const spyOnGetCases = jest.spyOn(api, 'getCaseConnectors');
const { waitFor } = renderHook(() => useGetCaseConnectors(caseId), {
renderHook(() => useGetCaseConnectors(caseId), {
wrapper: appMockRender.AppWrapper,
});
@ -50,7 +50,7 @@ describe('useGetCaseConnectors', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addSuccess, addError });
const { waitFor } = renderHook(() => useGetCaseConnectors(caseId), {
renderHook(() => useGetCaseConnectors(caseId), {
wrapper: appMockRender.AppWrapper,
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { basicCase } from './mock';
@ -37,12 +37,12 @@ describe('useGetCaseFileStats', () => {
});
it('calls filesClient.list with correct arguments', async () => {
const { waitForNextUpdate } = renderHook(() => useGetCaseFileStats(hookParams), {
renderHook(() => useGetCaseFileStats(hookParams), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
expect(appMockRender.getFilesClient().list).toHaveBeenCalledWith(expectedCallParams);
await waitFor(() =>
expect(appMockRender.getFilesClient().list).toHaveBeenCalledWith(expectedCallParams)
);
});
it('shows an error toast when filesClient.list throws', async () => {
@ -53,12 +53,12 @@ describe('useGetCaseFileStats', () => {
throw new Error('Something went wrong');
});
const { waitForNextUpdate } = renderHook(() => useGetCaseFileStats(hookParams), {
renderHook(() => useGetCaseFileStats(hookParams), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
expect(appMockRender.getFilesClient().list).toHaveBeenCalledWith(expectedCallParams);
expect(addError).toHaveBeenCalled();
await waitFor(() => {
expect(appMockRender.getFilesClient().list).toHaveBeenCalledWith(expectedCallParams);
expect(addError).toHaveBeenCalled();
});
});
});

View file

@ -5,7 +5,7 @@
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { basicCase } from './mock';
@ -48,22 +48,22 @@ describe('useGetCaseFiles', () => {
throw new Error('Something went wrong');
});
const { waitForNextUpdate } = renderHook(() => useGetCaseFiles(hookParams), {
renderHook(() => useGetCaseFiles(hookParams), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
expect(appMockRender.getFilesClient().list).toBeCalledWith(expectedCallParams);
expect(addError).toHaveBeenCalled();
await waitFor(() => {
expect(appMockRender.getFilesClient().list).toBeCalledWith(expectedCallParams);
expect(addError).toHaveBeenCalled();
});
});
it('calls filesClient.list with correct arguments', async () => {
const { waitForNextUpdate } = renderHook(() => useGetCaseFiles(hookParams), {
renderHook(() => useGetCaseFiles(hookParams), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
expect(appMockRender.getFilesClient().list).toBeCalledWith(expectedCallParams);
await waitFor(() =>
expect(appMockRender.getFilesClient().list).toBeCalledWith(expectedCallParams)
);
});
});

View file

@ -7,7 +7,7 @@
import type { FC, PropsWithChildren } from 'react';
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import type { SingleCaseMetricsFeature } from '../../common/ui';
import { useGetCaseMetrics } from './use_get_case_metrics';
import { basicCase } from './mock';
@ -34,12 +34,13 @@ describe('useGetCaseMetrics', () => {
it('calls getSingleCaseMetrics with correct arguments', async () => {
const spyOnGetCaseMetrics = jest.spyOn(api, 'getSingleCaseMetrics');
const { waitForNextUpdate } = renderHook(() => useGetCaseMetrics(basicCase.id, features), {
renderHook(() => useGetCaseMetrics(basicCase.id, features), {
wrapper,
});
await waitForNextUpdate();
expect(spyOnGetCaseMetrics).toBeCalledWith(basicCase.id, features, abortCtrl.signal);
await waitFor(() =>
expect(spyOnGetCaseMetrics).toBeCalledWith(basicCase.id, features, abortCtrl.signal)
);
});
it('shows an error toast when getSingleCaseMetrics throws', async () => {
@ -51,13 +52,13 @@ describe('useGetCaseMetrics', () => {
throw new Error('Something went wrong');
});
const { waitForNextUpdate } = renderHook(() => useGetCaseMetrics(basicCase.id, features), {
renderHook(() => useGetCaseMetrics(basicCase.id, features), {
wrapper,
});
await waitForNextUpdate();
expect(spyOnGetCaseMetrics).toBeCalledWith(basicCase.id, features, abortCtrl.signal);
expect(addError).toHaveBeenCalled();
await waitFor(() => {
expect(spyOnGetCaseMetrics).toBeCalledWith(basicCase.id, features, abortCtrl.signal);
expect(addError).toHaveBeenCalled();
});
});
});

View file

@ -4,7 +4,8 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import { renderHook } from '@testing-library/react-hooks';
import { waitFor, renderHook } from '@testing-library/react';
import { useToasts } from '../common/lib/kibana';
import type { AppMockRenderer } from '../common/mock';
@ -31,12 +32,11 @@ describe('useGetCaseUserActionsStats', () => {
});
it('returns proper state on getCaseUserActionsStats', async () => {
const { result, waitForNextUpdate } = renderHook(
() => useGetCaseUserActionsStats(basicCase.id),
{ wrapper: appMockRender.AppWrapper }
);
const { result } = renderHook(() => useGetCaseUserActionsStats(basicCase.id), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
await waitFor(() => expect(result.current.isLoading).toBe(false));
expect(result.current).toEqual(
expect.objectContaining({
@ -61,25 +61,23 @@ describe('useGetCaseUserActionsStats', () => {
const addError = jest.fn();
(useToasts as jest.Mock).mockReturnValue({ addError });
const { waitForNextUpdate } = renderHook(() => useGetCaseUserActionsStats(basicCase.id), {
renderHook(() => useGetCaseUserActionsStats(basicCase.id), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
expect(spy).toHaveBeenCalledWith(basicCase.id, expect.any(AbortSignal));
expect(addError).toHaveBeenCalled();
await waitFor(() => {
expect(spy).toHaveBeenCalledWith(basicCase.id, expect.any(AbortSignal));
expect(addError).toHaveBeenCalled();
});
});
it('calls the api when invoked with the correct parameters', async () => {
const spy = jest.spyOn(api, 'getCaseUserActionsStats');
const { waitForNextUpdate } = renderHook(() => useGetCaseUserActionsStats(basicCase.id), {
renderHook(() => useGetCaseUserActionsStats(basicCase.id), {
wrapper: appMockRender.AppWrapper,
});
await waitForNextUpdate();
expect(spy).toHaveBeenCalledWith(basicCase.id, expect.any(AbortSignal));
await waitFor(() => expect(spy).toHaveBeenCalledWith(basicCase.id, expect.any(AbortSignal)));
});
});

Some files were not shown because too many files have changed in this diff Show more