mirror of
https://github.com/elastic/kibana.git
synced 2025-04-23 17:28:26 -04:00
[React18] Migrate test suites to account for testing library upgrades security-threat-hunting-explore (#201142)
This PR migrates test suites that use `renderHook` from the library `@testing-library/react-hooks` to adopt the equivalent and replacement of `renderHook` from the export that is now available from `@testing-library/react`. This work is required for the planned migration to react18. ## Context In this PR, usages of `waitForNextUpdate` that previously could have been destructured from `renderHook` are now been replaced with `waitFor` exported from `@testing-library/react`, furthermore `waitFor` that would also have been destructured from the same renderHook result is now been replaced with `waitFor` from the export of `@testing-library/react`. ***Why is `waitFor` a sufficient enough replacement for `waitForNextUpdate`, and better for testing values subject to async computations?*** WaitFor will retry the provided callback if an error is returned, till the configured timeout elapses. By default the retry interval is `50ms` with a timeout value of `1000ms` that effectively translates to at least 20 retries for assertions placed within waitFor. See https://testing-library.com/docs/dom-testing-library/api-async/#waitfor for more information. This however means that for person's writing tests, said person has to be explicit about expectations that describe the internal state of the hook being tested. This implies checking for instance when a react query hook is being rendered, there's an assertion that said hook isn't loading anymore. In this PR you'd notice that this pattern has been adopted, with most existing assertions following an invocation of `waitForNextUpdate` being placed within a `waitFor` invocation. In some cases the replacement is simply a `waitFor(() => new Promise((resolve) => resolve(null)))` (many thanks to @kapral18, for point out exactly why this works), where this suffices the assertions that follow aren't placed within a waitFor so this PR doesn't get larger than it needs to be. It's also worth pointing out this PR might also contain changes to test and application code to improve said existing test. ### What to do next? 1. Review the changes in this PR. 2. If you think the changes are correct, approve the PR. ## Any questions? If you have any questions or need help with this PR, please leave comments in this PR. --------- Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com> Co-authored-by: Karen Grigoryan <karen.grigoryan@elastic.co> Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
This commit is contained in:
parent
4d8f7111d0
commit
da2ede4839
55 changed files with 999 additions and 994 deletions
|
@ -7,7 +7,7 @@
|
|||
* License v3.0 only", or the "Server Side Public License, v 1".
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import React, { type PropsWithChildren } from 'react';
|
||||
import { makeAction, makeActionContext } from '../mocks/helpers';
|
||||
import { CellActionsProvider, useCellActionsContext } from './cell_actions_context';
|
||||
|
@ -29,9 +29,8 @@ describe('CellActionContext', () => {
|
|||
});
|
||||
|
||||
it('should throw error when context not found', () => {
|
||||
const { result } = renderHook(useCellActionsContext);
|
||||
expect(result.error).toEqual(
|
||||
new Error('No CellActionsContext found. Please wrap the application with CellActionsProvider')
|
||||
expect(() => renderHook(useCellActionsContext)).toThrow(
|
||||
/No CellActionsContext found. Please wrap the application with CellActionsProvider/
|
||||
);
|
||||
});
|
||||
|
||||
|
|
|
@ -11,8 +11,7 @@ import type { JSXElementConstructor, MutableRefObject } from 'react';
|
|||
import React from 'react';
|
||||
import type { EuiDataGridColumnCellActionProps, EuiDataGridRefProps } from '@elastic/eui';
|
||||
import { EuiButtonEmpty, type EuiDataGridColumnCellAction } from '@elastic/eui';
|
||||
import { render, waitFor } from '@testing-library/react';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { render, waitFor, renderHook } from '@testing-library/react';
|
||||
import { makeAction } from '../mocks/helpers';
|
||||
import type { UseDataGridColumnsCellActionsProps } from './use_data_grid_column_cell_actions';
|
||||
import { useDataGridColumnsCellActions } from './use_data_grid_column_cell_actions';
|
||||
|
@ -72,75 +71,88 @@ describe('useDataGridColumnsCellActions', () => {
|
|||
});
|
||||
|
||||
it('should return array with actions for each columns', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useDataGridColumnsCellActions, {
|
||||
const { result } = renderHook(useDataGridColumnsCellActions, {
|
||||
initialProps: useDataGridColumnsCellActionsProps,
|
||||
});
|
||||
|
||||
expect(result.current).toHaveLength(0);
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.current).toHaveLength(columns.length);
|
||||
expect(result.current[0]).toHaveLength(actions.length);
|
||||
await waitFor(() => {
|
||||
expect(result.current).toHaveLength(columns.length);
|
||||
expect(result.current[0]).toHaveLength(actions.length);
|
||||
});
|
||||
});
|
||||
|
||||
it('should call getCellValue with the proper params', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useDataGridColumnsCellActions, {
|
||||
const { result } = renderHook(useDataGridColumnsCellActions, {
|
||||
initialProps: useDataGridColumnsCellActionsProps,
|
||||
});
|
||||
|
||||
await waitForNextUpdate();
|
||||
await waitFor(() => {
|
||||
expect(result.current).toHaveLength(columns.length);
|
||||
});
|
||||
|
||||
renderCellAction(result.current[0][0], { rowIndex: 0 });
|
||||
renderCellAction(result.current[0][1], { rowIndex: 1 });
|
||||
renderCellAction(result.current[1][0], { rowIndex: 0 });
|
||||
renderCellAction(result.current[1][1], { rowIndex: 1 });
|
||||
|
||||
expect(mockGetCellValue).toHaveBeenCalledTimes(4);
|
||||
expect(mockGetCellValue).toHaveBeenCalledWith(field1.name, 0);
|
||||
expect(mockGetCellValue).toHaveBeenCalledWith(field1.name, 1);
|
||||
expect(mockGetCellValue).toHaveBeenCalledWith(field2.name, 0);
|
||||
expect(mockGetCellValue).toHaveBeenCalledWith(field2.name, 1);
|
||||
await waitFor(() => {
|
||||
expect(mockGetCellValue).toHaveBeenCalledTimes(4);
|
||||
expect(mockGetCellValue).toHaveBeenCalledWith(field1.name, 0);
|
||||
expect(mockGetCellValue).toHaveBeenCalledWith(field1.name, 1);
|
||||
expect(mockGetCellValue).toHaveBeenCalledWith(field2.name, 0);
|
||||
expect(mockGetCellValue).toHaveBeenCalledWith(field2.name, 1);
|
||||
});
|
||||
});
|
||||
|
||||
it('should render the cell actions', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useDataGridColumnsCellActions, {
|
||||
const { result } = renderHook(useDataGridColumnsCellActions, {
|
||||
initialProps: useDataGridColumnsCellActionsProps,
|
||||
});
|
||||
|
||||
await waitForNextUpdate();
|
||||
await waitFor(() => {
|
||||
expect(result.current).toHaveLength(columns.length);
|
||||
});
|
||||
|
||||
const cellAction1 = renderCellAction(result.current[0][0]);
|
||||
|
||||
expect(cellAction1.getByTestId(`dataGridColumnCellAction-${action1.id}`)).toBeInTheDocument();
|
||||
expect(cellAction1.getByText(action1.getDisplayName())).toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(cellAction1.getByTestId(`dataGridColumnCellAction-${action1.id}`)).toBeInTheDocument();
|
||||
expect(cellAction1.getByText(action1.getDisplayName())).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const cellAction2 = renderCellAction(result.current[0][1]);
|
||||
|
||||
expect(cellAction2.getByTestId(`dataGridColumnCellAction-${action2.id}`)).toBeInTheDocument();
|
||||
expect(cellAction2.getByText(action2.getDisplayName())).toBeInTheDocument();
|
||||
await waitFor(() => {
|
||||
expect(cellAction2.getByTestId(`dataGridColumnCellAction-${action2.id}`)).toBeInTheDocument();
|
||||
expect(cellAction2.getByText(action2.getDisplayName())).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('should execute the action on click', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useDataGridColumnsCellActions, {
|
||||
const { result } = renderHook(useDataGridColumnsCellActions, {
|
||||
initialProps: useDataGridColumnsCellActionsProps,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
|
||||
const cellAction = renderCellAction(result.current[0][0]);
|
||||
await waitFor(() => {
|
||||
const cellAction = renderCellAction(result.current[0][0]);
|
||||
cellAction.getByTestId(`dataGridColumnCellAction-${action1.id}`).click();
|
||||
});
|
||||
|
||||
cellAction.getByTestId(`dataGridColumnCellAction-${action1.id}`).click();
|
||||
|
||||
waitFor(() => {
|
||||
await waitFor(() => {
|
||||
expect(action1.execute).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should execute the action with correct context', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useDataGridColumnsCellActions, {
|
||||
const { result } = renderHook(useDataGridColumnsCellActions, {
|
||||
initialProps: useDataGridColumnsCellActionsProps,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toHaveLength(columns.length);
|
||||
});
|
||||
|
||||
const cellAction1 = renderCellAction(result.current[0][0], { rowIndex: 1 });
|
||||
|
||||
|
@ -194,18 +206,19 @@ describe('useDataGridColumnsCellActions', () => {
|
|||
});
|
||||
|
||||
it('should execute the action with correct page value', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useDataGridColumnsCellActions, {
|
||||
const { result } = renderHook(useDataGridColumnsCellActions, {
|
||||
initialProps: useDataGridColumnsCellActionsProps,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
|
||||
const cellAction = renderCellAction(result.current[0][0], { rowIndex: 25 });
|
||||
|
||||
cellAction.getByTestId(`dataGridColumnCellAction-${action1.id}`).click();
|
||||
|
||||
expect(mockGetCellValue).toHaveBeenCalledWith(field1.name, 25);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toHaveLength(columns.length);
|
||||
});
|
||||
|
||||
const cellAction = renderCellAction(result.current[0][0], { rowIndex: 25 });
|
||||
cellAction.getByTestId(`dataGridColumnCellAction-${action1.id}`).click();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockGetCellValue).toHaveBeenCalledWith(field1.name, 25);
|
||||
expect(action1.execute).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: [
|
||||
|
@ -225,13 +238,15 @@ describe('useDataGridColumnsCellActions', () => {
|
|||
});
|
||||
|
||||
it('should close popover then action executed', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useDataGridColumnsCellActions, {
|
||||
const { result } = renderHook(useDataGridColumnsCellActions, {
|
||||
initialProps: useDataGridColumnsCellActionsProps,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toHaveLength(columns.length);
|
||||
});
|
||||
|
||||
const cellAction = renderCellAction(result.current[0][0], { rowIndex: 25 });
|
||||
|
||||
cellAction.getByTestId(`dataGridColumnCellAction-${action1.id}`).click();
|
||||
|
||||
await waitFor(() => {
|
||||
|
@ -240,30 +255,30 @@ describe('useDataGridColumnsCellActions', () => {
|
|||
});
|
||||
|
||||
it('should return empty array of actions when list of fields is empty', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useDataGridColumnsCellActions, {
|
||||
const { result } = renderHook(useDataGridColumnsCellActions, {
|
||||
initialProps: {
|
||||
...useDataGridColumnsCellActionsProps,
|
||||
fields: [],
|
||||
},
|
||||
});
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.current).toBeInstanceOf(Array);
|
||||
expect(result.current.length).toBe(0);
|
||||
await waitFor(() => {
|
||||
expect(result.current).toBeInstanceOf(Array);
|
||||
expect(result.current.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('should return empty array of actions when list of fields is undefined', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useDataGridColumnsCellActions, {
|
||||
const { result } = renderHook(useDataGridColumnsCellActions, {
|
||||
initialProps: {
|
||||
...useDataGridColumnsCellActionsProps,
|
||||
fields: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.current).toBeInstanceOf(Array);
|
||||
expect(result.current.length).toBe(0);
|
||||
await waitFor(() => {
|
||||
expect(result.current).toBeInstanceOf(Array);
|
||||
expect(result.current.length).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -7,7 +7,8 @@
|
|||
* License v3.0 only", or the "Server Side Public License, v 1".
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import React from 'react';
|
||||
import { waitFor, renderHook, act, screen } from '@testing-library/react';
|
||||
import { makeAction, makeActionContext } from '../mocks/helpers';
|
||||
import { useBulkLoadActions, useLoadActions, useLoadActionsFn } from './use_load_actions';
|
||||
|
||||
|
@ -17,6 +18,22 @@ jest.mock('../context/cell_actions_context', () => ({
|
|||
useCellActionsContext: () => ({ getActions: mockGetActions }),
|
||||
}));
|
||||
|
||||
class ErrorCatcher extends React.Component<React.PropsWithChildren> {
|
||||
state: { error: Error | null } = { error: null };
|
||||
|
||||
static getDerivedStateFromError(error: Error) {
|
||||
return { error };
|
||||
}
|
||||
|
||||
render() {
|
||||
return this.state.error ? (
|
||||
<div data-test-subj="leaf-error">{this.state.error.toString()}</div>
|
||||
) : (
|
||||
this.props.children
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
describe('loadActions hooks', () => {
|
||||
const actionContext = makeActionContext();
|
||||
|
||||
|
@ -26,7 +43,7 @@ describe('loadActions hooks', () => {
|
|||
});
|
||||
describe('useLoadActions', () => {
|
||||
it('should load actions when called', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useLoadActions, {
|
||||
const { result } = renderHook(useLoadActions, {
|
||||
initialProps: actionContext,
|
||||
});
|
||||
|
||||
|
@ -35,22 +52,24 @@ describe('loadActions hooks', () => {
|
|||
expect(mockGetActions).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetActions).toHaveBeenCalledWith(actionContext);
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.current.value).toEqual([action]);
|
||||
expect(result.current.loading).toEqual(false);
|
||||
await waitFor(() => {
|
||||
expect(result.current.value).toEqual([action]);
|
||||
expect(result.current.loading).toEqual(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw error when getAction is rejected', async () => {
|
||||
const message = 'some division by 0';
|
||||
mockGetActions.mockRejectedValueOnce(Error(message));
|
||||
|
||||
const { result, waitForNextUpdate } = renderHook(useLoadActions, {
|
||||
const { result } = renderHook(useLoadActions, {
|
||||
initialProps: actionContext,
|
||||
wrapper: ErrorCatcher, // Error prints any received error to the screen
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.error?.message).toEqual(message);
|
||||
expect(result.current.loading).toEqual(true);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('leaf-error')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('filters out disabled actions', async () => {
|
||||
|
@ -58,19 +77,17 @@ describe('loadActions hooks', () => {
|
|||
const actionDisabled = makeAction('action-disabled');
|
||||
mockGetActions.mockResolvedValue([actionEnabled, actionDisabled]);
|
||||
|
||||
const { result, waitForNextUpdate } = renderHook(() =>
|
||||
const { result } = renderHook(() =>
|
||||
useLoadActions(actionContext, { disabledActionTypes: [actionDisabled.type] })
|
||||
);
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.current.value).toEqual([actionEnabled]);
|
||||
await waitFor(() => expect(result.current.value).toEqual([actionEnabled]));
|
||||
});
|
||||
});
|
||||
|
||||
describe('useLoadActionsFn', () => {
|
||||
it('should load actions when returned function is called', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useLoadActionsFn);
|
||||
const { result } = renderHook(useLoadActionsFn);
|
||||
const [{ value: valueBeforeCall, loading: loadingBeforeCall }, loadActions] = result.current;
|
||||
|
||||
expect(valueBeforeCall).toBeUndefined();
|
||||
|
@ -87,28 +104,27 @@ describe('loadActions hooks', () => {
|
|||
expect(mockGetActions).toHaveBeenCalledTimes(1);
|
||||
expect(mockGetActions).toHaveBeenCalledWith(actionContext);
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
const [{ value: valueAfterUpdate, loading: loadingAfterUpdate }] = result.current;
|
||||
expect(valueAfterUpdate).toEqual([action]);
|
||||
expect(loadingAfterUpdate).toEqual(false);
|
||||
await waitFor(() => {
|
||||
const [{ value: valueAfterUpdate, loading: loadingAfterUpdate }] = result.current;
|
||||
expect(valueAfterUpdate).toEqual([action]);
|
||||
expect(loadingAfterUpdate).toEqual(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw error when getAction is rejected', async () => {
|
||||
const message = 'some division by 0';
|
||||
mockGetActions.mockRejectedValueOnce(Error(message));
|
||||
mockGetActions.mockRejectedValueOnce(new Error(message));
|
||||
|
||||
const { result, waitForNextUpdate } = renderHook(useLoadActionsFn);
|
||||
const { result } = renderHook(useLoadActionsFn, {
|
||||
wrapper: ErrorCatcher, // Error prints any received error to the screen
|
||||
});
|
||||
const [_, loadActions] = result.current;
|
||||
|
||||
expect(result.error).toBeUndefined();
|
||||
|
||||
act(() => {
|
||||
loadActions(actionContext);
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.error?.message).toEqual(message);
|
||||
await waitFor(() => expect(screen.getByTestId('leaf-error')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('filters out disabled actions types', async () => {
|
||||
|
@ -116,7 +132,7 @@ describe('loadActions hooks', () => {
|
|||
const actionDisabled = makeAction('action-disabled');
|
||||
mockGetActions.mockResolvedValue([actionEnabled, actionDisabled]);
|
||||
|
||||
const { result, waitForNextUpdate } = renderHook(() =>
|
||||
const { result } = renderHook(() =>
|
||||
useLoadActionsFn({ disabledActionTypes: [actionDisabled.type] })
|
||||
);
|
||||
const [_, loadActions] = result.current;
|
||||
|
@ -124,10 +140,10 @@ describe('loadActions hooks', () => {
|
|||
act(() => {
|
||||
loadActions(actionContext);
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
|
||||
const [{ value: valueAfterUpdate }] = result.current;
|
||||
expect(valueAfterUpdate).toEqual([actionEnabled]);
|
||||
await waitFor(() => {
|
||||
const [{ value: valueAfterUpdate }] = result.current;
|
||||
expect(valueAfterUpdate).toEqual([actionEnabled]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -136,7 +152,7 @@ describe('loadActions hooks', () => {
|
|||
const actionContexts = [actionContext, actionContext2];
|
||||
|
||||
it('should load bulk actions array when called', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(useBulkLoadActions, {
|
||||
const { result } = renderHook(useBulkLoadActions, {
|
||||
initialProps: actionContexts,
|
||||
});
|
||||
|
||||
|
@ -146,22 +162,24 @@ describe('loadActions hooks', () => {
|
|||
expect(mockGetActions).toHaveBeenCalledWith(actionContext);
|
||||
expect(mockGetActions).toHaveBeenCalledWith(actionContext2);
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.current.value).toEqual([[action], [action]]);
|
||||
expect(result.current.loading).toEqual(false);
|
||||
await waitFor(() => {
|
||||
expect(result.current.value).toEqual([[action], [action]]);
|
||||
expect(result.current.loading).toEqual(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should throw error when getAction is rejected', async () => {
|
||||
const message = 'some division by 0';
|
||||
mockGetActions.mockRejectedValueOnce(Error(message));
|
||||
|
||||
const { result, waitForNextUpdate } = renderHook(useBulkLoadActions, {
|
||||
const { result } = renderHook(useBulkLoadActions, {
|
||||
initialProps: actionContexts,
|
||||
wrapper: ErrorCatcher, // Error prints any received error to the screen
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.error?.message).toEqual(message);
|
||||
expect(result.current.loading).toEqual(true);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('leaf-error')).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('filters out disabled actions types', async () => {
|
||||
|
@ -169,40 +187,37 @@ describe('loadActions hooks', () => {
|
|||
const actionDisabled = makeAction('action-disabled');
|
||||
mockGetActions.mockResolvedValue([actionEnabled, actionDisabled]);
|
||||
|
||||
const { result, waitForNextUpdate } = renderHook(() =>
|
||||
const { result } = renderHook(() =>
|
||||
useBulkLoadActions(actionContexts, { disabledActionTypes: [actionDisabled.type] })
|
||||
);
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.current.value).toEqual([[actionEnabled], [actionEnabled]]);
|
||||
await waitFor(() => expect(result.current.value).toEqual([[actionEnabled], [actionEnabled]]));
|
||||
});
|
||||
|
||||
it('should re-render when contexts is changed', async () => {
|
||||
const { result, rerender, waitForNextUpdate } = renderHook(useBulkLoadActions, {
|
||||
const { result, rerender } = renderHook(useBulkLoadActions, {
|
||||
initialProps: [actionContext],
|
||||
});
|
||||
|
||||
await waitForNextUpdate();
|
||||
expect(mockGetActions).toHaveBeenCalledWith(actionContext);
|
||||
await waitFor(() => expect(mockGetActions).toHaveBeenCalledWith(actionContext));
|
||||
|
||||
rerender([actionContext2]);
|
||||
await waitForNextUpdate();
|
||||
expect(mockGetActions).toHaveBeenCalledWith(actionContext2);
|
||||
await waitFor(() => expect(mockGetActions).toHaveBeenCalledWith(actionContext2));
|
||||
|
||||
mockGetActions.mockClear();
|
||||
|
||||
rerender([]);
|
||||
await waitForNextUpdate();
|
||||
expect(mockGetActions).toHaveBeenCalledTimes(0);
|
||||
await waitFor(() => {
|
||||
expect(mockGetActions).toHaveBeenCalledTimes(0);
|
||||
|
||||
expect(result.current.value).toBeInstanceOf(Array);
|
||||
expect(result.current.value).toHaveLength(0);
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.value).toBeInstanceOf(Array);
|
||||
expect(result.current.value).toHaveLength(0);
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it('should return the same array after re-render when contexts is undefined', async () => {
|
||||
const { result, rerender, waitFor } = renderHook(useBulkLoadActions, {
|
||||
const { result, rerender } = renderHook(useBulkLoadActions, {
|
||||
initialProps: undefined,
|
||||
});
|
||||
|
|
@ -7,7 +7,7 @@
|
|||
|
||||
import { Theme } from '@elastic/charts';
|
||||
import { notificationServiceMock } from '@kbn/core-notifications-browser-mocks';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import React, { FC, PropsWithChildren } from 'react';
|
||||
|
||||
import { DataQualityProvider, useDataQualityContext } from '.';
|
||||
|
@ -78,9 +78,7 @@ describe('DataQualityContext', () => {
|
|||
});
|
||||
|
||||
test('it throws an error when useDataQualityContext hook is used without a DataQualityContext', () => {
|
||||
const { result } = renderHook(useDataQualityContext);
|
||||
|
||||
expect(result.error).toEqual(
|
||||
expect(() => renderHook(useDataQualityContext)).toThrow(
|
||||
new Error('useDataQualityContext must be used within a DataQualityProvider')
|
||||
);
|
||||
});
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
|
||||
import { mockHistoricalResult } from '../../../../../mock/historical_results/mock_historical_results_response';
|
||||
import { TestDataQualityProviders } from '../../../../../mock/test_providers/test_providers';
|
||||
|
|
|
@ -5,13 +5,13 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { waitFor, renderHook } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
|
||||
import { DataQualityProvider } from '../../../../../data_quality_context';
|
||||
import { mockIlmExplain } from '../../../../../mock/ilm_explain/mock_ilm_explain';
|
||||
import { ERROR_LOADING_ILM_EXPLAIN } from '../../../../../translations';
|
||||
import { useIlmExplain, UseIlmExplain } from '.';
|
||||
import { useIlmExplain } from '.';
|
||||
import { notificationServiceMock } from '@kbn/core-notifications-browser-mocks';
|
||||
import { Theme } from '@elastic/charts';
|
||||
|
||||
|
@ -23,60 +23,62 @@ const mockTelemetryEvents = {
|
|||
reportDataQualityCheckAllCompleted: mockReportDataQualityCheckAllClicked,
|
||||
};
|
||||
const { toasts } = notificationServiceMock.createSetupContract();
|
||||
const ContextWrapper: React.FC<{ children: React.ReactNode; isILMAvailable: boolean }> = ({
|
||||
const ContextWrapper: React.FC<React.PropsWithChildren<{ isILMAvailable?: boolean }>> = ({
|
||||
children,
|
||||
isILMAvailable = true,
|
||||
}) => (
|
||||
<DataQualityProvider
|
||||
httpFetch={mockHttpFetch}
|
||||
telemetryEvents={mockTelemetryEvents}
|
||||
isILMAvailable={isILMAvailable}
|
||||
toasts={toasts}
|
||||
addSuccessToast={jest.fn()}
|
||||
canUserCreateAndReadCases={jest.fn(() => true)}
|
||||
endDate={null}
|
||||
formatBytes={jest.fn()}
|
||||
formatNumber={jest.fn()}
|
||||
isAssistantEnabled={true}
|
||||
lastChecked={'2023-03-28T22:27:28.159Z'}
|
||||
openCreateCaseFlyout={jest.fn()}
|
||||
patterns={['auditbeat-*']}
|
||||
setLastChecked={jest.fn()}
|
||||
startDate={null}
|
||||
theme={{
|
||||
background: {
|
||||
color: '#000',
|
||||
},
|
||||
}}
|
||||
baseTheme={
|
||||
{
|
||||
}) => {
|
||||
return (
|
||||
<DataQualityProvider
|
||||
httpFetch={mockHttpFetch}
|
||||
telemetryEvents={mockTelemetryEvents}
|
||||
isILMAvailable={isILMAvailable}
|
||||
toasts={toasts}
|
||||
addSuccessToast={jest.fn()}
|
||||
canUserCreateAndReadCases={jest.fn(() => true)}
|
||||
endDate={null}
|
||||
formatBytes={jest.fn()}
|
||||
formatNumber={jest.fn()}
|
||||
isAssistantEnabled={true}
|
||||
lastChecked={'2023-03-28T22:27:28.159Z'}
|
||||
openCreateCaseFlyout={jest.fn()}
|
||||
patterns={['auditbeat-*']}
|
||||
setLastChecked={jest.fn()}
|
||||
startDate={null}
|
||||
theme={{
|
||||
background: {
|
||||
color: '#000',
|
||||
},
|
||||
} as Theme
|
||||
}
|
||||
ilmPhases={['hot', 'warm', 'unmanaged']}
|
||||
selectedIlmPhaseOptions={[
|
||||
{
|
||||
label: 'Hot',
|
||||
value: 'hot',
|
||||
},
|
||||
{
|
||||
label: 'Warm',
|
||||
value: 'warm',
|
||||
},
|
||||
{
|
||||
label: 'Unmanaged',
|
||||
value: 'unmanaged',
|
||||
},
|
||||
]}
|
||||
setSelectedIlmPhaseOptions={jest.fn()}
|
||||
defaultStartTime={'now-7d'}
|
||||
defaultEndTime={'now'}
|
||||
>
|
||||
{children}
|
||||
</DataQualityProvider>
|
||||
);
|
||||
}}
|
||||
baseTheme={
|
||||
{
|
||||
background: {
|
||||
color: '#000',
|
||||
},
|
||||
} as Theme
|
||||
}
|
||||
ilmPhases={['hot', 'warm', 'unmanaged']}
|
||||
selectedIlmPhaseOptions={[
|
||||
{
|
||||
label: 'Hot',
|
||||
value: 'hot',
|
||||
},
|
||||
{
|
||||
label: 'Warm',
|
||||
value: 'warm',
|
||||
},
|
||||
{
|
||||
label: 'Unmanaged',
|
||||
value: 'unmanaged',
|
||||
},
|
||||
]}
|
||||
setSelectedIlmPhaseOptions={jest.fn()}
|
||||
defaultStartTime={'now-7d'}
|
||||
defaultEndTime={'now'}
|
||||
>
|
||||
{children}
|
||||
</DataQualityProvider>
|
||||
);
|
||||
};
|
||||
|
||||
const pattern = 'packetbeat-*';
|
||||
|
||||
|
@ -86,125 +88,107 @@ describe('useIlmExplain', () => {
|
|||
});
|
||||
|
||||
describe('successful response from the ilm api', () => {
|
||||
let ilmExplainResult: UseIlmExplain | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
function setup() {
|
||||
mockHttpFetch.mockResolvedValue(mockIlmExplain);
|
||||
|
||||
const { result, waitForNextUpdate } = renderHook(() => useIlmExplain(pattern), {
|
||||
return renderHook(() => useIlmExplain(pattern), {
|
||||
wrapper: ContextWrapper,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
ilmExplainResult = await result.current;
|
||||
});
|
||||
}
|
||||
|
||||
test('it returns the expected ilmExplain map', async () => {
|
||||
expect(ilmExplainResult?.ilmExplain).toEqual(mockIlmExplain);
|
||||
const { result } = setup();
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.ilmExplain).toEqual(mockIlmExplain);
|
||||
});
|
||||
});
|
||||
|
||||
test('it returns loading: false, because the data has loaded', async () => {
|
||||
expect(ilmExplainResult?.loading).toBe(false);
|
||||
const { result } = setup();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(true);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
test('it returns a null error, because no errors occurred', async () => {
|
||||
expect(ilmExplainResult?.error).toBeNull();
|
||||
const { result } = setup();
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('skip ilm api when isILMAvailable is false', () => {
|
||||
let ilmExplainResult: UseIlmExplain | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useIlmExplain(pattern), {
|
||||
wrapper: ({ children }: React.PropsWithChildren<{}>) => (
|
||||
<DataQualityProvider
|
||||
httpFetch={mockHttpFetch}
|
||||
telemetryEvents={mockTelemetryEvents}
|
||||
isILMAvailable={false}
|
||||
toasts={toasts}
|
||||
addSuccessToast={jest.fn()}
|
||||
canUserCreateAndReadCases={jest.fn(() => true)}
|
||||
endDate={null}
|
||||
formatBytes={jest.fn()}
|
||||
formatNumber={jest.fn()}
|
||||
isAssistantEnabled={true}
|
||||
lastChecked={'2023-03-28T22:27:28.159Z'}
|
||||
openCreateCaseFlyout={jest.fn()}
|
||||
patterns={['auditbeat-*']}
|
||||
setLastChecked={jest.fn()}
|
||||
startDate={null}
|
||||
theme={{
|
||||
background: {
|
||||
color: '#000',
|
||||
},
|
||||
}}
|
||||
baseTheme={
|
||||
{
|
||||
background: {
|
||||
color: '#000',
|
||||
},
|
||||
} as Theme
|
||||
}
|
||||
ilmPhases={['hot', 'warm', 'unmanaged']}
|
||||
selectedIlmPhaseOptions={[
|
||||
{
|
||||
label: 'Hot',
|
||||
value: 'hot',
|
||||
},
|
||||
{
|
||||
label: 'Warm',
|
||||
value: 'warm',
|
||||
},
|
||||
{
|
||||
label: 'Unmanaged',
|
||||
value: 'unmanaged',
|
||||
},
|
||||
]}
|
||||
setSelectedIlmPhaseOptions={jest.fn()}
|
||||
defaultStartTime={'now-7d'}
|
||||
defaultEndTime={'now'}
|
||||
>
|
||||
{children}
|
||||
</DataQualityProvider>
|
||||
),
|
||||
function setup() {
|
||||
mockHttpFetch.mockResolvedValue(mockIlmExplain);
|
||||
return renderHook(() => useIlmExplain(pattern), {
|
||||
wrapper: (props) => <ContextWrapper {...props} isILMAvailable={false} />,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
ilmExplainResult = await result.current;
|
||||
});
|
||||
}
|
||||
|
||||
test('it returns the expected ilmExplain map', async () => {
|
||||
expect(ilmExplainResult?.ilmExplain).toEqual(null);
|
||||
const { result } = setup();
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.ilmExplain).toEqual(null);
|
||||
});
|
||||
});
|
||||
|
||||
test('it returns loading: false, because the request is aborted', async () => {
|
||||
expect(ilmExplainResult?.loading).toBe(false);
|
||||
const { result } = setup();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(true);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetch rejects with an error', () => {
|
||||
let ilmExplainResult: UseIlmExplain | undefined;
|
||||
const errorMessage = 'simulated error';
|
||||
|
||||
beforeEach(async () => {
|
||||
function setup() {
|
||||
mockHttpFetch.mockRejectedValue(new Error(errorMessage));
|
||||
|
||||
const { result, waitForNextUpdate } = renderHook(() => useIlmExplain(pattern), {
|
||||
return renderHook(() => useIlmExplain(pattern), {
|
||||
wrapper: ContextWrapper,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
ilmExplainResult = await result.current;
|
||||
});
|
||||
}
|
||||
|
||||
test('it returns a null ilmExplain, because an error occurred', async () => {
|
||||
expect(ilmExplainResult?.ilmExplain).toBeNull();
|
||||
const { result } = setup();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.ilmExplain).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
test('it returns loading: false, because data loading reached a terminal state', async () => {
|
||||
expect(ilmExplainResult?.loading).toBe(false);
|
||||
const { result } = setup();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(true);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
test('it returns the expected error', async () => {
|
||||
expect(ilmExplainResult?.error).toEqual(ERROR_LOADING_ILM_EXPLAIN(errorMessage));
|
||||
const { result } = setup();
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.error).toEqual(ERROR_LOADING_ILM_EXPLAIN(errorMessage));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -5,12 +5,12 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { waitFor, renderHook } from '@testing-library/react';
|
||||
import React, { FC, PropsWithChildren } from 'react';
|
||||
|
||||
import { DataQualityProvider } from '../../../../../data_quality_context';
|
||||
import { ERROR_LOADING_STATS } from '../../../../../translations';
|
||||
import { useStats, UseStats } from '.';
|
||||
import { useStats } from '.';
|
||||
import { notificationServiceMock } from '@kbn/core-notifications-browser-mocks';
|
||||
import { Theme } from '@elastic/charts';
|
||||
import { mockStatsAuditbeatIndex } from '../../../../../mock/stats/mock_stats_auditbeat_index';
|
||||
|
@ -24,63 +24,14 @@ const mockTelemetryEvents = {
|
|||
};
|
||||
const { toasts } = notificationServiceMock.createSetupContract();
|
||||
|
||||
const ContextWrapper: FC<PropsWithChildren<unknown>> = ({ children }) => (
|
||||
const ContextWrapper: FC<PropsWithChildren<{ isILMAvailable?: boolean }>> = ({
|
||||
children,
|
||||
isILMAvailable = true,
|
||||
}) => (
|
||||
<DataQualityProvider
|
||||
httpFetch={mockHttpFetch}
|
||||
telemetryEvents={mockTelemetryEvents}
|
||||
isILMAvailable={true}
|
||||
toasts={toasts}
|
||||
addSuccessToast={jest.fn()}
|
||||
canUserCreateAndReadCases={jest.fn(() => true)}
|
||||
endDate={null}
|
||||
formatBytes={jest.fn()}
|
||||
formatNumber={jest.fn()}
|
||||
isAssistantEnabled={true}
|
||||
lastChecked={'2023-03-28T22:27:28.159Z'}
|
||||
openCreateCaseFlyout={jest.fn()}
|
||||
patterns={['auditbeat-*']}
|
||||
setLastChecked={jest.fn()}
|
||||
startDate={null}
|
||||
theme={{
|
||||
background: {
|
||||
color: '#000',
|
||||
},
|
||||
}}
|
||||
baseTheme={
|
||||
{
|
||||
background: {
|
||||
color: '#000',
|
||||
},
|
||||
} as Theme
|
||||
}
|
||||
ilmPhases={['hot', 'warm', 'unmanaged']}
|
||||
selectedIlmPhaseOptions={[
|
||||
{
|
||||
label: 'Hot',
|
||||
value: 'hot',
|
||||
},
|
||||
{
|
||||
label: 'Warm',
|
||||
value: 'warm',
|
||||
},
|
||||
{
|
||||
label: 'Unmanaged',
|
||||
value: 'unmanaged',
|
||||
},
|
||||
]}
|
||||
setSelectedIlmPhaseOptions={jest.fn()}
|
||||
defaultStartTime={'now-7d'}
|
||||
defaultEndTime={'now'}
|
||||
>
|
||||
{children}
|
||||
</DataQualityProvider>
|
||||
);
|
||||
|
||||
const ContextWrapperILMNotAvailable: FC<PropsWithChildren<unknown>> = ({ children }) => (
|
||||
<DataQualityProvider
|
||||
httpFetch={mockHttpFetch}
|
||||
telemetryEvents={mockTelemetryEvents}
|
||||
isILMAvailable={false}
|
||||
isILMAvailable={isILMAvailable}
|
||||
toasts={toasts}
|
||||
addSuccessToast={jest.fn()}
|
||||
canUserCreateAndReadCases={jest.fn(() => true)}
|
||||
|
@ -141,79 +92,113 @@ describe('useStats', () => {
|
|||
});
|
||||
|
||||
describe('query with date range when ILM is not available', () => {
|
||||
const queryParams = {
|
||||
isILMAvailable: false,
|
||||
startDate,
|
||||
endDate,
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
test('it calls the stats api with the expected params', async () => {
|
||||
mockHttpFetch.mockResolvedValue(mockStatsAuditbeatIndex);
|
||||
|
||||
const { waitForNextUpdate } = renderHook(() => useStats({ pattern, startDate, endDate }), {
|
||||
wrapper: ContextWrapperILMNotAvailable,
|
||||
const queryParams = {
|
||||
isILMAvailable: false,
|
||||
startDate,
|
||||
endDate,
|
||||
};
|
||||
|
||||
renderHook(() => useStats({ pattern, startDate, endDate }), {
|
||||
wrapper: ({ children }) => (
|
||||
<ContextWrapper isILMAvailable={false}>{children}</ContextWrapper>
|
||||
),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockHttpFetch.mock.calls[0][1].query).toEqual(queryParams);
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
});
|
||||
test(`it calls the stats api with the expected params`, async () => {
|
||||
expect(mockHttpFetch.mock.calls[0][1].query).toEqual(queryParams);
|
||||
});
|
||||
});
|
||||
|
||||
describe('successful response from the stats api', () => {
|
||||
let statsResult: UseStats | undefined;
|
||||
|
||||
beforeEach(async () => {
|
||||
function setup() {
|
||||
mockHttpFetch.mockResolvedValue(mockStatsAuditbeatIndex);
|
||||
|
||||
const { result, waitForNextUpdate } = renderHook(() => useStats(params), {
|
||||
const { result } = renderHook(() => useStats(params), {
|
||||
wrapper: ContextWrapper,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
statsResult = await result.current;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
test('it returns the expected stats', async () => {
|
||||
expect(statsResult?.stats).toEqual(mockStatsAuditbeatIndex);
|
||||
const result = setup();
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.stats).toEqual(mockStatsAuditbeatIndex);
|
||||
});
|
||||
});
|
||||
|
||||
test('it returns loading: false, because the data has loaded', async () => {
|
||||
expect(statsResult?.loading).toBe(false);
|
||||
const result = setup();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(true);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
test('it returns a null error, because no errors occurred', async () => {
|
||||
expect(statsResult?.error).toBeNull();
|
||||
const result = setup();
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
test(`it calls the stats api with the expected params`, async () => {
|
||||
expect(mockHttpFetch.mock.calls[0][1].query).toEqual({ isILMAvailable: true });
|
||||
test('it calls the stats api with the expected params', async () => {
|
||||
setup();
|
||||
await waitFor(() => {
|
||||
expect(mockHttpFetch.mock.calls[0][1].query).toEqual({ isILMAvailable: true });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetch rejects with an error', () => {
|
||||
let statsResult: UseStats | undefined;
|
||||
const errorMessage = 'simulated error';
|
||||
|
||||
beforeEach(async () => {
|
||||
function setup() {
|
||||
mockHttpFetch.mockRejectedValue(new Error(errorMessage));
|
||||
|
||||
const { result, waitForNextUpdate } = renderHook(() => useStats(params), {
|
||||
const { result } = renderHook(() => useStats(params), {
|
||||
wrapper: ContextWrapper,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
statsResult = await result.current;
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
test('it returns null stats, because an error occurred', async () => {
|
||||
expect(statsResult?.stats).toBeNull();
|
||||
const result = setup();
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.stats).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
test('it returns loading: false, because data loading reached a terminal state', async () => {
|
||||
expect(statsResult?.loading).toBe(false);
|
||||
const result = setup();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(true);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
test('it returns the expected error', async () => {
|
||||
expect(statsResult?.error).toEqual(ERROR_LOADING_STATS(errorMessage));
|
||||
const result = setup();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.error).toEqual(ERROR_LOADING_STATS(errorMessage));
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -5,10 +5,8 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook, act } from '@testing-library/react-hooks';
|
||||
|
||||
import { useCurrentWindowWidth } from '.';
|
||||
import { fireEvent } from '@testing-library/react';
|
||||
import { fireEvent, renderHook, act } from '@testing-library/react';
|
||||
|
||||
describe('useCurrentWidthWidth', () => {
|
||||
beforeEach(() => {
|
||||
|
@ -20,7 +18,6 @@ describe('useCurrentWidthWidth', () => {
|
|||
});
|
||||
it('return current window width', () => {
|
||||
const { result } = renderHook(() => useCurrentWindowWidth());
|
||||
expect(result.error).toBeUndefined();
|
||||
expect(result.current).toBe(window.innerWidth);
|
||||
});
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useAbortControllerRef } from '.';
|
||||
|
||||
describe('useAbortControllerRef', () => {
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { act, waitFor, renderHook } from '@testing-library/react';
|
||||
|
||||
import { useIndicesCheck } from '.';
|
||||
|
||||
|
@ -82,9 +82,7 @@ describe('useIndicesCheck', () => {
|
|||
|
||||
describe('when checkIndex completes', () => {
|
||||
it('should set correct data', async () => {
|
||||
const { result, waitFor } = renderHook(() =>
|
||||
useIndicesCheck({ onCheckCompleted: jest.fn() })
|
||||
);
|
||||
const { result } = renderHook(() => useIndicesCheck({ onCheckCompleted: jest.fn() }));
|
||||
|
||||
const httpFetchMock = jest.fn((route) => {
|
||||
if (route.startsWith('/internal/ecs_data_quality_dashboard/mappings')) {
|
||||
|
@ -124,9 +122,7 @@ describe('useIndicesCheck', () => {
|
|||
describe('errors', () => {
|
||||
describe('when mappings request errors', () => {
|
||||
it('should set mappingsError', async () => {
|
||||
const { result, waitFor } = renderHook(() =>
|
||||
useIndicesCheck({ onCheckCompleted: jest.fn() })
|
||||
);
|
||||
const { result } = renderHook(() => useIndicesCheck({ onCheckCompleted: jest.fn() }));
|
||||
|
||||
const httpFetchMock = jest.fn((route) => {
|
||||
if (route.startsWith('/internal/ecs_data_quality_dashboard/mappings')) {
|
||||
|
@ -160,9 +156,7 @@ describe('useIndicesCheck', () => {
|
|||
|
||||
describe('when unallowed values request errors', () => {
|
||||
it('should set unallowedValuesError', async () => {
|
||||
const { result, waitFor } = renderHook(() =>
|
||||
useIndicesCheck({ onCheckCompleted: jest.fn() })
|
||||
);
|
||||
const { result } = renderHook(() => useIndicesCheck({ onCheckCompleted: jest.fn() }));
|
||||
|
||||
const httpFetchMock = jest.fn((route) => {
|
||||
if (route.startsWith('/internal/ecs_data_quality_dashboard/mappings')) {
|
||||
|
@ -232,9 +226,7 @@ describe('useIndicesCheck', () => {
|
|||
onStart?.();
|
||||
});
|
||||
|
||||
const { result, waitFor } = renderHook(() =>
|
||||
useIndicesCheck({ onCheckCompleted: jest.fn() })
|
||||
);
|
||||
const { result } = renderHook(() => useIndicesCheck({ onCheckCompleted: jest.fn() }));
|
||||
|
||||
act(() =>
|
||||
result.current.checkIndex({
|
||||
|
@ -257,7 +249,7 @@ describe('useIndicesCheck', () => {
|
|||
});
|
||||
|
||||
describe('when mappings are loading', () => {
|
||||
it('it should set isLoadingMappings to true', () => {
|
||||
it('it should set isLoadingMappings to true', async () => {
|
||||
const { checkIndexSpy } = getSpies();
|
||||
|
||||
checkIndexSpy.mockImplementation(async ({ onStart, onLoadMappingsStart }) => {
|
||||
|
@ -265,9 +257,7 @@ describe('useIndicesCheck', () => {
|
|||
onLoadMappingsStart?.();
|
||||
});
|
||||
|
||||
const { result, waitFor } = renderHook(() =>
|
||||
useIndicesCheck({ onCheckCompleted: jest.fn() })
|
||||
);
|
||||
const { result } = renderHook(() => useIndicesCheck({ onCheckCompleted: jest.fn() }));
|
||||
|
||||
act(() =>
|
||||
result.current.checkIndex({
|
||||
|
@ -280,7 +270,7 @@ describe('useIndicesCheck', () => {
|
|||
})
|
||||
);
|
||||
|
||||
waitFor(() =>
|
||||
await waitFor(() =>
|
||||
expect(result.current.checkState['auditbeat-custom-index-1']).toEqual({
|
||||
...getInitialCheckStateValue(),
|
||||
isChecking: true,
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
|
||||
import { useIsMountedRef } from '.';
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { notificationServiceMock } from '@kbn/core-notifications-browser-mocks';
|
||||
|
||||
import { getHistoricalResultStub } from '../../../../stub/get_historical_result_stub';
|
||||
|
@ -57,7 +57,7 @@ describe('useStoredPatternResults', () => {
|
|||
return Promise.reject(new Error('Invalid path'));
|
||||
});
|
||||
|
||||
const { result, waitFor } = renderHook(() =>
|
||||
const { result } = renderHook(() =>
|
||||
useStoredPatternResults({
|
||||
patterns,
|
||||
toasts: mockToasts,
|
||||
|
@ -68,7 +68,7 @@ describe('useStoredPatternResults', () => {
|
|||
})
|
||||
);
|
||||
|
||||
await waitFor(() => result.current.length > 0);
|
||||
await waitFor(() => expect(result.current.length).toBeGreaterThan(0));
|
||||
|
||||
expect(httpFetch).toHaveBeenCalledTimes(2);
|
||||
|
||||
|
@ -141,7 +141,7 @@ describe('useStoredPatternResults', () => {
|
|||
return Promise.reject(new Error('Invalid path'));
|
||||
});
|
||||
|
||||
const { result, waitFor } = renderHook(() =>
|
||||
const { result } = renderHook(() =>
|
||||
useStoredPatternResults({
|
||||
patterns,
|
||||
toasts: mockToasts,
|
||||
|
@ -152,7 +152,7 @@ describe('useStoredPatternResults', () => {
|
|||
})
|
||||
);
|
||||
|
||||
await waitFor(() => result.current.length > 0);
|
||||
await waitFor(() => expect(result.current.length).toBeGreaterThan(0));
|
||||
|
||||
expect(httpFetch).toHaveBeenCalledTimes(2);
|
||||
|
||||
|
|
|
@ -9,7 +9,7 @@
|
|||
// so when tests are run in different timezones, the results are consistent
|
||||
process.env.TZ = 'UTC';
|
||||
|
||||
import { renderHook, act } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { notificationServiceMock } from '@kbn/core-notifications-browser-mocks';
|
||||
|
||||
import type { TelemetryEvents } from '../../types';
|
||||
|
|
|
@ -5,8 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
import React from 'react';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { render } from '@testing-library/react';
|
||||
import { render, renderHook } from '@testing-library/react';
|
||||
import {
|
||||
useGetLinkUrl,
|
||||
useGetLinkProps,
|
||||
|
|
|
@ -6,8 +6,7 @@
|
|||
*/
|
||||
import { useGetAppUrl, useNavigateTo } from './navigation';
|
||||
import { mockGetUrlForApp, mockNavigateToApp, mockNavigateToUrl } from '../mocks/context';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { fireEvent } from '@testing-library/react';
|
||||
import { fireEvent, renderHook } from '@testing-library/react';
|
||||
|
||||
jest.mock('./context');
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { mockTimelineModel } from '../../../common/mock/timeline_results';
|
||||
import { useFormatUrl } from '../../../common/components/link_to';
|
||||
|
|
|
@ -7,7 +7,7 @@
|
|||
|
||||
import { shallow } from 'enzyme';
|
||||
import React from 'react';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { useDarkMode } from '../../lib/kibana';
|
||||
import type { ChartSeriesData } from './common';
|
||||
|
|
|
@ -5,11 +5,12 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { waitFor, act, renderHook } from '@testing-library/react';
|
||||
import { of } from 'rxjs';
|
||||
|
||||
import { siemGuideId } from '../../../../common/guided_onboarding/siem_guide_config';
|
||||
import { TourContextProvider, useTourContext } from './tour';
|
||||
import { SecurityStepId, securityTourConfig } from './tour_config';
|
||||
import { type AlertsCasesTourSteps, SecurityStepId, securityTourConfig } from './tour_config';
|
||||
import { useKibana } from '../../lib/kibana';
|
||||
|
||||
jest.mock('../../lib/kibana');
|
||||
|
@ -44,7 +45,7 @@ describe('useTourContext', () => {
|
|||
// @ts-ignore
|
||||
const tourIds = [SecurityStepId.alertsCases];
|
||||
describe.each(tourIds)('%s', (tourId: SecurityStepId) => {
|
||||
it('if guidedOnboardingApi?.isGuideStepActive$ is false, isTourShown should be false', () => {
|
||||
it('if guidedOnboardingApi?.isGuideStepActive$ is false, isTourShown should be false', async () => {
|
||||
(useKibana as jest.Mock).mockReturnValue({
|
||||
services: {
|
||||
guidedOnboarding: {
|
||||
|
@ -57,66 +58,80 @@ describe('useTourContext', () => {
|
|||
const { result } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
expect(result.current.isTourShown(tourId)).toBe(false);
|
||||
await waitFor(() => {
|
||||
expect(result.current.isTourShown(tourId)).toBe(false);
|
||||
});
|
||||
});
|
||||
it('if guidedOnboardingApi?.isGuideStepActive$ is true, isTourShown should be true', () => {
|
||||
it('if guidedOnboardingApi?.isGuideStepActive$ is true, isTourShown should be true', async () => {
|
||||
const { result } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
expect(result.current.isTourShown(tourId)).toBe(true);
|
||||
await waitFor(() => {
|
||||
expect(result.current.isTourShown(tourId)).toBe(true);
|
||||
});
|
||||
});
|
||||
it('endTourStep calls completeGuideStep with correct tourId', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
act(() => {
|
||||
result.current.endTourStep(tourId);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(mockCompleteGuideStep).toHaveBeenCalledWith(siemGuideId, tourId);
|
||||
});
|
||||
});
|
||||
it('activeStep is initially 1', () => {
|
||||
it('activeStep is initially 1', async () => {
|
||||
const { result } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
expect(result.current.activeStep).toBe(1);
|
||||
await waitFor(() => {
|
||||
expect(result.current.activeStep).toBe(1);
|
||||
});
|
||||
});
|
||||
it('incrementStep properly increments for each tourId, and if attempted to increment beyond length of tour config steps resets activeStep to 1', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
const stepCount = securityTourConfig[tourId].length;
|
||||
const { result } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
const stepCount = securityTourConfig[tourId].length;
|
||||
act(() => {
|
||||
for (let i = 0; i < stepCount - 1; i++) {
|
||||
result.current.incrementStep(tourId);
|
||||
}
|
||||
const lastStep = stepCount ? stepCount : 1;
|
||||
});
|
||||
const lastStep = stepCount ? stepCount : 1;
|
||||
await waitFor(() => {
|
||||
expect(result.current.activeStep).toBe(lastStep);
|
||||
});
|
||||
act(() => {
|
||||
result.current.incrementStep(tourId);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.activeStep).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
it('setStep sets activeStep to step number argument', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
act(() => {
|
||||
result.current.setStep(tourId, 6);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.activeStep).toBe(6);
|
||||
});
|
||||
});
|
||||
|
||||
it('does not setStep sets activeStep to non-existing step number', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
// @ts-expect-error testing invalid step
|
||||
result.current.setStep(tourId, 88);
|
||||
const { result } = renderHook(() => useTourContext(), {
|
||||
wrapper: TourContextProvider,
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.setStep(tourId, 88 as AlertsCasesTourSteps);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.activeStep).toBe(1);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import type { ReactChild } from 'react';
|
||||
import type { FC, ReactNode } from 'react';
|
||||
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
import useObservable from 'react-use/lib/useObservable';
|
||||
|
@ -39,7 +39,7 @@ const initialState: TourContextValue = {
|
|||
|
||||
const TourContext = createContext<TourContextValue>(initialState);
|
||||
|
||||
export const RealTourContextProvider = ({ children }: { children: ReactChild }) => {
|
||||
export const RealTourContextProvider: FC<{ children: ReactNode }> = ({ children }) => {
|
||||
const { guidedOnboarding } = useKibana().services;
|
||||
const [hidden, setHidden] = useState(false);
|
||||
|
||||
|
@ -131,7 +131,7 @@ export const RealTourContextProvider = ({ children }: { children: ReactChild })
|
|||
return <TourContext.Provider value={context}>{children}</TourContext.Provider>;
|
||||
};
|
||||
|
||||
export const TourContextProvider = ({ children }: { children: ReactChild }) => {
|
||||
export const TourContextProvider: FC<{ children: ReactNode }> = ({ children }) => {
|
||||
const { pathname } = useLocation();
|
||||
|
||||
const ContextProvider = useMemo(
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import type { ChromeBreadcrumb } from '@kbn/core/public';
|
||||
import type { GetSecuritySolutionUrl } from '../../link_to';
|
||||
import { SecurityPageName } from '../../../../../common/constants';
|
||||
|
|
|
@ -6,8 +6,7 @@
|
|||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { render, renderHook } from '@testing-library/react';
|
||||
import { of } from 'rxjs';
|
||||
import { useSecuritySolutionNavigation } from './use_security_solution_navigation';
|
||||
|
||||
|
|
|
@ -4,17 +4,14 @@
|
|||
* 2.0; you may not use this file except in compliance with the Elastic License
|
||||
* 2.0.
|
||||
*/
|
||||
import type { MutableRefObject } from 'react';
|
||||
import React from 'react';
|
||||
import type { RenderHookResult } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import type { RenderHookResult } from '@testing-library/react';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { TestProviders } from '../../mock';
|
||||
import { useKibana } from '../../lib/kibana';
|
||||
import { InputsModelId } from '../../store/inputs/constants';
|
||||
import { useRefetchByRestartingSession } from './use_refetch_by_session';
|
||||
import { inputsActions } from '../../store/actions';
|
||||
import type { Refetch } from '../../store/inputs/model';
|
||||
import type { ISessionService } from '@kbn/data-plugin/public';
|
||||
|
||||
const wrapper = ({ children }: { children: React.ReactNode }) => (
|
||||
<TestProviders>{children}</TestProviders>
|
||||
|
@ -45,13 +42,8 @@ jest.mock('../../store/actions', () => {
|
|||
|
||||
describe(`useRefetchByRestartingSession`, () => {
|
||||
let res: RenderHookResult<
|
||||
{
|
||||
children: React.ReactNode;
|
||||
},
|
||||
{
|
||||
session: MutableRefObject<ISessionService>;
|
||||
refetchByRestartingSession: Refetch;
|
||||
}
|
||||
ReturnType<typeof useRefetchByRestartingSession>,
|
||||
Parameters<typeof useRefetchByRestartingSession>[0]
|
||||
>;
|
||||
const mockSessionStart = jest.fn().mockReturnValue('mockSessionId');
|
||||
const mockSession = {
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
import type { HttpStart } from '@kbn/core/public';
|
||||
import { renderHook, act } from '@testing-library/react-hooks';
|
||||
import { waitFor, renderHook } from '@testing-library/react';
|
||||
import { DashboardContextProvider } from '../context/dashboard_context';
|
||||
import { useFetchSecurityDashboards } from './use_fetch_security_dashboards';
|
||||
import { getTagsByName } from '../../common/containers/tags/api';
|
||||
|
@ -26,14 +26,6 @@ const renderUseFetchSecurityDashboards = () =>
|
|||
wrapper: DashboardContextProvider,
|
||||
});
|
||||
|
||||
const asyncRenderUseFetchSecurityDashboards = async () => {
|
||||
const renderedHook = renderUseFetchSecurityDashboards();
|
||||
await act(async () => {
|
||||
await renderedHook.waitForNextUpdate();
|
||||
});
|
||||
return renderedHook;
|
||||
};
|
||||
|
||||
describe('useFetchSecurityDashboards', () => {
|
||||
beforeAll(() => {
|
||||
useKibana().services.http = mockHttp as unknown as HttpStart;
|
||||
|
@ -49,34 +41,43 @@ describe('useFetchSecurityDashboards', () => {
|
|||
});
|
||||
|
||||
it('should fetch Security Solution tags', async () => {
|
||||
await asyncRenderUseFetchSecurityDashboards();
|
||||
expect(getTagsByName).toHaveBeenCalledTimes(1);
|
||||
renderUseFetchSecurityDashboards();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getTagsByName).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it('should fetch Security Solution dashboards', async () => {
|
||||
await asyncRenderUseFetchSecurityDashboards();
|
||||
renderUseFetchSecurityDashboards();
|
||||
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledTimes(1);
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledWith(
|
||||
{
|
||||
http: mockHttp,
|
||||
tagIds: [MOCK_TAG_ID],
|
||||
},
|
||||
expect.any(Object)
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledTimes(1);
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledWith(
|
||||
{
|
||||
http: mockHttp,
|
||||
tagIds: [MOCK_TAG_ID],
|
||||
},
|
||||
expect.any(Object)
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should fetch Security Solution dashboards with abort signal', async () => {
|
||||
await asyncRenderUseFetchSecurityDashboards();
|
||||
renderUseFetchSecurityDashboards();
|
||||
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledTimes(1);
|
||||
expect((getDashboardsByTagIds as jest.Mock).mock.calls[0][1]).toEqual(mockAbortSignal);
|
||||
await waitFor(() => {
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledTimes(1);
|
||||
expect((getDashboardsByTagIds as jest.Mock).mock.calls[0][1]).toEqual(mockAbortSignal);
|
||||
});
|
||||
});
|
||||
|
||||
it('should return Security Solution dashboards', async () => {
|
||||
const { result } = await asyncRenderUseFetchSecurityDashboards();
|
||||
const { result } = renderUseFetchSecurityDashboards();
|
||||
|
||||
expect(result.current.isLoading).toEqual(false);
|
||||
expect(result.current.dashboards).toEqual(DEFAULT_DASHBOARDS_RESPONSE);
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toEqual(false);
|
||||
expect(result.current.dashboards).toEqual(DEFAULT_DASHBOARDS_RESPONSE);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
*/
|
||||
|
||||
import type { HttpStart } from '@kbn/core/public';
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { waitFor, renderHook } from '@testing-library/react';
|
||||
import {
|
||||
INTERNAL_TAGS_URL,
|
||||
SECURITY_TAG_DESCRIPTION,
|
||||
|
@ -28,14 +28,6 @@ const mockAbortSignal = {} as unknown as AbortSignal;
|
|||
const mockCreateTag = jest.fn();
|
||||
const renderUseCreateSecurityDashboardLink = () => renderHook(() => useFetchSecurityTags(), {});
|
||||
|
||||
const asyncRenderUseCreateSecurityDashboardLink = async () => {
|
||||
const renderedHook = renderUseCreateSecurityDashboardLink();
|
||||
await act(async () => {
|
||||
await renderedHook.waitForNextUpdate();
|
||||
});
|
||||
return renderedHook;
|
||||
};
|
||||
|
||||
describe('useFetchSecurityTags', () => {
|
||||
beforeAll(() => {
|
||||
useKibana().services.http = { get: mockGet } as unknown as HttpStart;
|
||||
|
@ -54,25 +46,31 @@ describe('useFetchSecurityTags', () => {
|
|||
|
||||
test('should fetch Security Solution tags', async () => {
|
||||
mockGet.mockResolvedValue([]);
|
||||
await asyncRenderUseCreateSecurityDashboardLink();
|
||||
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
INTERNAL_TAGS_URL,
|
||||
expect.objectContaining({
|
||||
query: { name: SECURITY_TAG_NAME },
|
||||
signal: mockAbortSignal,
|
||||
})
|
||||
);
|
||||
renderUseCreateSecurityDashboardLink();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockGet).toHaveBeenCalledWith(
|
||||
INTERNAL_TAGS_URL,
|
||||
expect.objectContaining({
|
||||
query: { name: SECURITY_TAG_NAME },
|
||||
signal: mockAbortSignal,
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('should create a Security Solution tag if no Security Solution tags were found', async () => {
|
||||
mockGet.mockResolvedValue([]);
|
||||
await asyncRenderUseCreateSecurityDashboardLink();
|
||||
|
||||
expect(mockCreateTag).toHaveBeenCalledWith({
|
||||
name: SECURITY_TAG_NAME,
|
||||
description: SECURITY_TAG_DESCRIPTION,
|
||||
color: '#FFFFFF',
|
||||
renderUseCreateSecurityDashboardLink();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockCreateTag).toHaveBeenCalledWith({
|
||||
name: SECURITY_TAG_NAME,
|
||||
description: SECURITY_TAG_DESCRIPTION,
|
||||
color: '#FFFFFF',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -84,9 +82,11 @@ describe('useFetchSecurityTags', () => {
|
|||
type: 'tag',
|
||||
...tag.attributes,
|
||||
}));
|
||||
const { result } = await asyncRenderUseCreateSecurityDashboardLink();
|
||||
const { result } = renderUseCreateSecurityDashboardLink();
|
||||
|
||||
expect(mockCreateTag).not.toHaveBeenCalled();
|
||||
expect(result.current.tags).toEqual(expect.objectContaining(expected));
|
||||
await waitFor(() => {
|
||||
expect(mockCreateTag).not.toHaveBeenCalled();
|
||||
expect(result.current.tags).toEqual(expect.objectContaining(expected));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook, act } from '@testing-library/react-hooks';
|
||||
import { act, waitFor, renderHook } from '@testing-library/react';
|
||||
import { useKibana } from '../../common/lib/kibana';
|
||||
import { useCreateSecurityDashboardLink } from './use_create_security_dashboard_link';
|
||||
import { DashboardContextProvider } from '../context/dashboard_context';
|
||||
|
@ -34,15 +34,6 @@ const renderUseCreateSecurityDashboardLink = () =>
|
|||
),
|
||||
});
|
||||
|
||||
const asyncRenderUseCreateSecurityDashboard = async () => {
|
||||
const renderedHook = renderUseCreateSecurityDashboardLink();
|
||||
|
||||
await act(async () => {
|
||||
await renderedHook.waitForNextUpdate();
|
||||
});
|
||||
return renderedHook;
|
||||
};
|
||||
|
||||
describe('useCreateSecurityDashboardLink', () => {
|
||||
beforeAll(() => {
|
||||
(useKibana as jest.Mock).mockReturnValue({
|
||||
|
@ -61,40 +52,51 @@ describe('useCreateSecurityDashboardLink', () => {
|
|||
|
||||
describe('useSecurityDashboardsTableItems', () => {
|
||||
it('should fetch Security Solution tags when renders', async () => {
|
||||
await asyncRenderUseCreateSecurityDashboard();
|
||||
renderUseCreateSecurityDashboardLink();
|
||||
|
||||
expect(getTagsByName).toHaveBeenCalledTimes(1);
|
||||
await waitFor(() => {
|
||||
expect(getTagsByName).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it('should return a memoized value when rerendered', async () => {
|
||||
const { result, rerender } = await asyncRenderUseCreateSecurityDashboard();
|
||||
const { result, rerender } = renderUseCreateSecurityDashboardLink();
|
||||
|
||||
const result1 = result.current;
|
||||
act(() => rerender());
|
||||
const result2 = result.current;
|
||||
expect(result1).toEqual(result2);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result1).toEqual(result2);
|
||||
});
|
||||
});
|
||||
|
||||
it('should not re-request tag id when re-rendered', async () => {
|
||||
const { rerender } = await asyncRenderUseCreateSecurityDashboard();
|
||||
const { rerender } = renderUseCreateSecurityDashboardLink();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getTagsByName).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
expect(getTagsByName).toHaveBeenCalledTimes(1);
|
||||
act(() => rerender());
|
||||
expect(getTagsByName).toHaveBeenCalledTimes(1);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getTagsByName).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it('should return isLoading while requesting', async () => {
|
||||
const { result, waitForNextUpdate } = renderUseCreateSecurityDashboardLink();
|
||||
const { result } = renderUseCreateSecurityDashboardLink();
|
||||
|
||||
expect(result.current.isLoading).toEqual(true);
|
||||
expect(result.current.url).toEqual('/app/security/dashboards/create');
|
||||
|
||||
await act(async () => {
|
||||
await waitForNextUpdate();
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toEqual(true);
|
||||
expect(result.current.url).toEqual('/app/security/dashboards/create');
|
||||
});
|
||||
|
||||
expect(result.current.isLoading).toEqual(false);
|
||||
expect(result.current.url).toEqual('/app/security/dashboards/create');
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toEqual(false);
|
||||
expect(result.current.url).toEqual('/app/security/dashboards/create');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -4,7 +4,8 @@
|
|||
* 2.0; you may not use this file except in compliance with the Elastic License
|
||||
* 2.0.
|
||||
*/
|
||||
import { renderHook, act } from '@testing-library/react-hooks';
|
||||
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import type { DashboardApi } from '@kbn/dashboard-plugin/public';
|
||||
|
||||
import { useDashboardRenderer } from './use_dashboard_renderer';
|
||||
|
@ -14,11 +15,11 @@ jest.mock('../../common/lib/kibana');
|
|||
const mockDashboardContainer = {} as DashboardApi;
|
||||
|
||||
describe('useDashboardRenderer', () => {
|
||||
it('should set dashboard container correctly when dashboard is loaded', async () => {
|
||||
it('should set dashboard container correctly when dashboard is loaded', () => {
|
||||
const { result } = renderHook(() => useDashboardRenderer());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleDashboardLoaded(mockDashboardContainer);
|
||||
act(() => {
|
||||
result.current.handleDashboardLoaded(mockDashboardContainer);
|
||||
});
|
||||
|
||||
expect(result.current.dashboardContainer).toEqual(mockDashboardContainer);
|
||||
|
|
|
@ -4,8 +4,7 @@
|
|||
* 2.0; you may not use this file except in compliance with the Elastic License
|
||||
* 2.0.
|
||||
*/
|
||||
import type { EuiEmptyPromptProps } from '@elastic/eui';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import {
|
||||
DashboardViewPromptState,
|
||||
useDashboardViewPromptState,
|
||||
|
@ -13,18 +12,14 @@ import {
|
|||
|
||||
describe('useDashboardViewPromptState', () => {
|
||||
it('returns empty state', () => {
|
||||
const { result } = renderHook<
|
||||
DashboardViewPromptState | null,
|
||||
Partial<EuiEmptyPromptProps> | null
|
||||
>(() => useDashboardViewPromptState(null));
|
||||
const { result } = renderHook(() => useDashboardViewPromptState(null));
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
|
||||
it('returns NoReadPermission state', () => {
|
||||
const { result } = renderHook<
|
||||
DashboardViewPromptState | null,
|
||||
Partial<EuiEmptyPromptProps> | null
|
||||
>(() => useDashboardViewPromptState(DashboardViewPromptState.NoReadPermission));
|
||||
const { result } = renderHook(() =>
|
||||
useDashboardViewPromptState(DashboardViewPromptState.NoReadPermission)
|
||||
);
|
||||
expect(result.current).toMatchInlineSnapshot(`
|
||||
Object {
|
||||
"body": <p>
|
||||
|
|
|
@ -6,8 +6,7 @@
|
|||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { renderHook, act } from '@testing-library/react-hooks';
|
||||
import { render } from '@testing-library/react';
|
||||
import { render, waitFor, renderHook } from '@testing-library/react';
|
||||
import type { DashboardStart } from '@kbn/dashboard-plugin/public';
|
||||
import { EuiBasicTable } from '@elastic/eui';
|
||||
import { useKibana } from '../../common/lib/kibana';
|
||||
|
@ -28,21 +27,20 @@ import type { HttpStart } from '@kbn/core/public';
|
|||
jest.mock('../../common/lib/kibana');
|
||||
jest.mock('../../common/containers/tags/api');
|
||||
jest.mock('../../common/containers/dashboards/api');
|
||||
|
||||
const useKibanaMock = useKibana as jest.Mocked<typeof useKibana>;
|
||||
|
||||
const spyUseGetSecuritySolutionUrl = jest.spyOn(linkTo, 'useGetSecuritySolutionUrl');
|
||||
const spyTrack = jest.spyOn(telemetry, 'track');
|
||||
const {
|
||||
id: mockReturnDashboardId,
|
||||
attributes: { title: mockReturnDashboardTitle, description: mockReturnDashboardDescription },
|
||||
} = DEFAULT_DASHBOARDS_RESPONSE[0];
|
||||
const renderUseSecurityDashboardsTableItems = async () => {
|
||||
const renderedHook = renderHook(() => useSecurityDashboardsTableItems(), {
|
||||
|
||||
const renderUseSecurityDashboardsTableItems = () => {
|
||||
return renderHook(useSecurityDashboardsTableItems, {
|
||||
wrapper: DashboardContextProvider,
|
||||
});
|
||||
await act(async () => {
|
||||
// needed to let dashboard items to be updated from saved objects response
|
||||
await renderedHook.waitForNextUpdate();
|
||||
});
|
||||
return renderedHook;
|
||||
};
|
||||
|
||||
const renderUseDashboardsTableColumns = () =>
|
||||
|
@ -50,101 +48,137 @@ const renderUseDashboardsTableColumns = () =>
|
|||
wrapper: TestProviders,
|
||||
});
|
||||
|
||||
const tagsColumn = {
|
||||
field: 'id', // set existing field to prevent test error
|
||||
name: 'Tags',
|
||||
'data-test-subj': 'dashboardTableTagsCell',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Security Dashboards Table hooks', () => {
|
||||
const mockGetRedirectUrl = jest.fn(() => '/path');
|
||||
useKibana().services.dashboard = {
|
||||
locator: { getRedirectUrl: mockGetRedirectUrl },
|
||||
} as unknown as DashboardStart;
|
||||
useKibana().services.http = {} as unknown as HttpStart;
|
||||
let mockTaggingGetTableColumnDefinition: jest.Mock;
|
||||
|
||||
const mockTaggingGetTableColumnDefinition = useKibana().services.savedObjectsTagging?.ui
|
||||
.getTableColumnDefinition as jest.Mock;
|
||||
const tagsColumn = {
|
||||
field: 'id', // set existing field to prevent test error
|
||||
name: 'Tags',
|
||||
'data-test-subj': 'dashboardTableTagsCell',
|
||||
};
|
||||
mockTaggingGetTableColumnDefinition.mockReturnValue(tagsColumn);
|
||||
beforeEach(() => {
|
||||
useKibanaMock().services.dashboard = {
|
||||
locator: { getRedirectUrl: jest.fn(() => '/path') },
|
||||
} as unknown as DashboardStart;
|
||||
useKibanaMock().services.http = {} as unknown as HttpStart;
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockTaggingGetTableColumnDefinition = useKibanaMock().services.savedObjectsTagging?.ui
|
||||
.getTableColumnDefinition as jest.Mock;
|
||||
|
||||
mockTaggingGetTableColumnDefinition.mockReturnValue(tagsColumn);
|
||||
});
|
||||
|
||||
describe('useSecurityDashboardsTableItems', () => {
|
||||
it('should request when renders', async () => {
|
||||
await renderUseSecurityDashboardsTableItems();
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledTimes(1);
|
||||
renderUseSecurityDashboardsTableItems();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it('should not request again when rerendered', async () => {
|
||||
const { rerender } = await renderUseSecurityDashboardsTableItems();
|
||||
const { rerender } = renderUseSecurityDashboardsTableItems();
|
||||
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledTimes(1);
|
||||
act(() => rerender());
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledTimes(1);
|
||||
await waitFor(() => {
|
||||
expect(getDashboardsByTagIds).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
rerender();
|
||||
|
||||
await waitFor(() => {
|
||||
return expect(getDashboardsByTagIds).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
it('should return a memoized value when rerendered', async () => {
|
||||
const { result, rerender } = await renderUseSecurityDashboardsTableItems();
|
||||
const { result, rerender } = renderUseSecurityDashboardsTableItems();
|
||||
|
||||
waitFor(() => expect(result.current.isLoading).toBe(false));
|
||||
|
||||
const result1 = result.current.items;
|
||||
act(() => rerender());
|
||||
const result2 = result.current.items;
|
||||
|
||||
expect(result1).toBe(result2);
|
||||
rerender();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(result1).toBe(result.current.items);
|
||||
});
|
||||
});
|
||||
|
||||
it('should return dashboard items', async () => {
|
||||
const { result } = await renderUseSecurityDashboardsTableItems();
|
||||
const { result } = renderUseSecurityDashboardsTableItems();
|
||||
|
||||
const [dashboard1] = DEFAULT_DASHBOARDS_RESPONSE;
|
||||
expect(result.current.items).toStrictEqual([
|
||||
{
|
||||
...dashboard1,
|
||||
title: dashboard1.attributes.title,
|
||||
description: dashboard1.attributes.description,
|
||||
},
|
||||
]);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.items).toStrictEqual([
|
||||
{
|
||||
...dashboard1,
|
||||
title: dashboard1.attributes.title,
|
||||
description: dashboard1.attributes.description,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('useDashboardsTableColumns', () => {
|
||||
it('should call getTableColumnDefinition to get tags column', () => {
|
||||
it('should call getTableColumnDefinition to get tags column', async () => {
|
||||
renderUseDashboardsTableColumns();
|
||||
expect(mockTaggingGetTableColumnDefinition).toHaveBeenCalled();
|
||||
await waitFor(() => {
|
||||
expect(mockTaggingGetTableColumnDefinition).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('should return dashboard columns', () => {
|
||||
it('should return dashboard columns', async () => {
|
||||
const { result } = renderUseDashboardsTableColumns();
|
||||
|
||||
expect(result.current).toEqual([
|
||||
expect.objectContaining({
|
||||
field: 'title',
|
||||
name: 'Title',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
field: 'description',
|
||||
name: 'Description',
|
||||
}),
|
||||
expect.objectContaining(tagsColumn),
|
||||
]);
|
||||
await waitFor(() => {
|
||||
expect(result.current).toEqual([
|
||||
expect.objectContaining({
|
||||
field: 'title',
|
||||
name: 'Title',
|
||||
}),
|
||||
expect.objectContaining({
|
||||
field: 'description',
|
||||
name: 'Description',
|
||||
}),
|
||||
expect.objectContaining(tagsColumn),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it('returns a memoized value', async () => {
|
||||
const { result, rerender } = renderUseDashboardsTableColumns();
|
||||
|
||||
const result1 = result.current;
|
||||
act(() => rerender());
|
||||
|
||||
rerender();
|
||||
|
||||
const result2 = result.current;
|
||||
|
||||
expect(result1).toBe(result2);
|
||||
await waitFor(() => {
|
||||
expect(result1).toBe(result2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should render a table with consistent items and columns', async () => {
|
||||
const { result: itemsResult } = await renderUseSecurityDashboardsTableItems();
|
||||
const { result: itemsResult } = renderUseSecurityDashboardsTableItems();
|
||||
const { result: columnsResult } = renderUseDashboardsTableColumns();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(itemsResult.current.isLoading).toBe(false);
|
||||
expect(itemsResult.current.items).toHaveLength(1);
|
||||
expect(columnsResult.current).toHaveLength(3);
|
||||
});
|
||||
|
||||
const result = render(
|
||||
<EuiBasicTable items={itemsResult.current.items} columns={columnsResult.current} />,
|
||||
{
|
||||
|
@ -152,22 +186,28 @@ describe('Security Dashboards Table hooks', () => {
|
|||
}
|
||||
);
|
||||
|
||||
expect(result.getAllByText('Title').length).toBeGreaterThan(0);
|
||||
expect(result.getAllByText('Description').length).toBeGreaterThan(0);
|
||||
expect(result.getAllByText('Tags').length).toBeGreaterThan(0);
|
||||
expect(await result.findAllByText('Title')).toHaveLength(1);
|
||||
expect(await result.findAllByText('Description')).toHaveLength(1);
|
||||
expect(await result.findAllByText('Tags')).toHaveLength(1);
|
||||
|
||||
expect(result.getByText(mockReturnDashboardTitle)).toBeInTheDocument();
|
||||
expect(result.getByText(mockReturnDashboardDescription)).toBeInTheDocument();
|
||||
expect(await result.findByText(mockReturnDashboardTitle)).toBeInTheDocument();
|
||||
expect(await result.findByText(mockReturnDashboardDescription)).toBeInTheDocument();
|
||||
|
||||
expect(result.queryAllByTestId('dashboardTableTitleCell')).toHaveLength(1);
|
||||
expect(result.queryAllByTestId('dashboardTableDescriptionCell')).toHaveLength(1);
|
||||
expect(result.queryAllByTestId('dashboardTableTagsCell')).toHaveLength(1);
|
||||
expect(await result.findAllByTestId('dashboardTableTitleCell')).toHaveLength(1);
|
||||
expect(await result.findAllByTestId('dashboardTableDescriptionCell')).toHaveLength(1);
|
||||
expect(await result.findAllByTestId('dashboardTableTagsCell')).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should send telemetry when dashboard title clicked', async () => {
|
||||
const { result: itemsResult } = await renderUseSecurityDashboardsTableItems();
|
||||
const { result: itemsResult } = renderUseSecurityDashboardsTableItems();
|
||||
const { result: columnsResult } = renderUseDashboardsTableColumns();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(itemsResult.current.isLoading).toBe(false);
|
||||
expect(itemsResult.current.items).toHaveLength(1);
|
||||
expect(columnsResult.current).toHaveLength(3);
|
||||
});
|
||||
|
||||
const result = render(
|
||||
<EuiBasicTable items={itemsResult.current.items} columns={columnsResult.current} />,
|
||||
{
|
||||
|
@ -176,22 +216,33 @@ describe('Security Dashboards Table hooks', () => {
|
|||
);
|
||||
|
||||
result.getByText(mockReturnDashboardTitle).click();
|
||||
expect(spyTrack).toHaveBeenCalledWith(METRIC_TYPE.CLICK, TELEMETRY_EVENT.DASHBOARD);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(spyTrack).toHaveBeenCalledWith(METRIC_TYPE.CLICK, TELEMETRY_EVENT.DASHBOARD);
|
||||
});
|
||||
});
|
||||
|
||||
it('should land on SecuritySolution dashboard view page when dashboard title clicked', async () => {
|
||||
const mockGetSecuritySolutionUrl = jest.fn();
|
||||
spyUseGetSecuritySolutionUrl.mockImplementation(() => mockGetSecuritySolutionUrl);
|
||||
const { result: itemsResult } = await renderUseSecurityDashboardsTableItems();
|
||||
const { result: itemsResult } = renderUseSecurityDashboardsTableItems();
|
||||
const { result: columnsResult } = renderUseDashboardsTableColumns();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(itemsResult.current.isLoading).toBe(false);
|
||||
expect(itemsResult.current.items).toHaveLength(1);
|
||||
expect(columnsResult.current).toHaveLength(3);
|
||||
});
|
||||
|
||||
render(<EuiBasicTable items={itemsResult.current.items} columns={columnsResult.current} />, {
|
||||
wrapper: TestProviders,
|
||||
});
|
||||
|
||||
expect(mockGetSecuritySolutionUrl).toHaveBeenCalledWith({
|
||||
deepLinkId: SecurityPageName.dashboards,
|
||||
path: mockReturnDashboardId,
|
||||
await waitFor(() => {
|
||||
expect(mockGetSecuritySolutionUrl).toHaveBeenCalledWith({
|
||||
deepLinkId: SecurityPageName.dashboards,
|
||||
path: mockReturnDashboardId,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { waitFor, renderHook } from '@testing-library/react';
|
||||
import React from 'react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { useGroupTakeActionsItems } from '.';
|
||||
|
@ -20,68 +20,58 @@ describe('useGroupTakeActionsItems', () => {
|
|||
selectedGroup: 'test',
|
||||
};
|
||||
it('returns all take actions items if showAlertStatusActions is true and currentStatus is undefined', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
expect(result.current(getActionItemsParams).length).toEqual(3);
|
||||
});
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitFor(() => expect(result.current(getActionItemsParams).length).toEqual(3));
|
||||
});
|
||||
|
||||
it('returns all take actions items if currentStatus is []', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
currentStatus: [],
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
expect(result.current(getActionItemsParams).length).toEqual(3);
|
||||
});
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
currentStatus: [],
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitFor(() => expect(result.current(getActionItemsParams).length).toEqual(3));
|
||||
});
|
||||
|
||||
it('returns all take actions items if currentStatus.length > 1', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
currentStatus: ['open', 'closed'],
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
expect(result.current(getActionItemsParams).length).toEqual(3);
|
||||
});
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
currentStatus: ['open', 'closed'],
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitFor(() => expect(result.current(getActionItemsParams).length).toEqual(3));
|
||||
});
|
||||
|
||||
it('returns acknowledged & closed take actions items if currentStatus === ["open"]', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
currentStatus: ['open'],
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
currentStatus: ['open'],
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitFor(() => {
|
||||
const currentParams = result.current(getActionItemsParams);
|
||||
expect(currentParams.length).toEqual(2);
|
||||
expect(currentParams[0].key).toEqual('acknowledge');
|
||||
|
@ -90,18 +80,17 @@ describe('useGroupTakeActionsItems', () => {
|
|||
});
|
||||
|
||||
it('returns open & acknowledged take actions items if currentStatus === ["closed"]', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
currentStatus: ['closed'],
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
currentStatus: ['closed'],
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitFor(() => {
|
||||
const currentParams = result.current(getActionItemsParams);
|
||||
expect(currentParams.length).toEqual(2);
|
||||
expect(currentParams[0].key).toEqual('open');
|
||||
|
@ -110,18 +99,17 @@ describe('useGroupTakeActionsItems', () => {
|
|||
});
|
||||
|
||||
it('returns open & closed take actions items if currentStatus === ["acknowledged"]', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
currentStatus: ['acknowledged'],
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
currentStatus: ['acknowledged'],
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitFor(() => {
|
||||
const currentParams = result.current(getActionItemsParams);
|
||||
expect(currentParams.length).toEqual(2);
|
||||
expect(currentParams[0].key).toEqual('open');
|
||||
|
@ -130,33 +118,28 @@ describe('useGroupTakeActionsItems', () => {
|
|||
});
|
||||
|
||||
it('returns empty take actions items if showAlertStatusActions is false', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
showAlertStatusActions: false,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
expect(result.current(getActionItemsParams).length).toEqual(0);
|
||||
});
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
showAlertStatusActions: false,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitFor(() => expect(result.current(getActionItemsParams).length).toEqual(0));
|
||||
});
|
||||
|
||||
it('returns array take actions items if showAlertStatusActions is true', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
expect(result.current(getActionItemsParams).length).toEqual(3);
|
||||
});
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useGroupTakeActionsItems({
|
||||
showAlertStatusActions: true,
|
||||
}),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitFor(() => expect(result.current(getActionItemsParams).length).toEqual(3));
|
||||
});
|
||||
});
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useAuthentications } from '.';
|
||||
import { AuthStackByField } from '../../../../common/search_strategy';
|
||||
import { TestProviders } from '../../../common/mock';
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
*/
|
||||
import { useKibana } from '../../../common/lib/kibana';
|
||||
import { useIsFieldInIndexPattern } from '.';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { getRequiredMapsFields } from '../../network/components/embeddables/map_config';
|
||||
|
||||
jest.mock('../../../common/lib/kibana');
|
||||
|
|
|
@ -4,7 +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';
|
||||
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../../common/mock';
|
||||
import { ID, useHostDetails } from '.';
|
||||
import { useSearchStrategy } from '../../../../../common/containers/use_search_strategy';
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { useAllHost } from '.';
|
||||
import { HostsType } from '../../store/model';
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { useUncommonProcesses } from '.';
|
||||
import { HostsType } from '../../store/model';
|
||||
|
|
|
@ -4,7 +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';
|
||||
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { ID, useNetworkDetails } from '.';
|
||||
import { useSearchStrategy } from '../../../../common/containers/use_search_strategy';
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { ID, useNetworkDns } from '.';
|
||||
import { useSearchStrategy } from '../../../../common/containers/use_search_strategy';
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { useNetworkHttp, ID } from '.';
|
||||
import { useSearchStrategy } from '../../../../common/containers/use_search_strategy';
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { ID, useNetworkTopCountries } from '.';
|
||||
import { useSearchStrategy } from '../../../../common/containers/use_search_strategy';
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { ID, useNetworkTopNFlow } from '.';
|
||||
import { useSearchStrategy } from '../../../../common/containers/use_search_strategy';
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { ID, useNetworkTls } from '.';
|
||||
import { useSearchStrategy } from '../../../../common/containers/use_search_strategy';
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { useNetworkUsers, ID } from '.';
|
||||
import { useSearchStrategy } from '../../../../common/containers/use_search_strategy';
|
||||
|
|
|
@ -4,7 +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';
|
||||
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../../common/mock';
|
||||
import { useObservedUserDetails } from '.';
|
||||
import { useSearchStrategy } from '../../../../../common/containers/use_search_strategy';
|
||||
|
|
|
@ -5,12 +5,11 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import type { PropsWithChildren } from 'react';
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import { ALERTS_QUERY_NAMES } from '../../../../detections/containers/detection_engine/alerts/constants';
|
||||
import { from, mockAlertsData, alertsByStatusQuery, parsedMockAlertsData, to } from './mock_data';
|
||||
import type { UseAlertsByStatus, UseAlertsByStatusProps } from './use_alerts_by_status';
|
||||
import type { UseAlertsByStatusProps } from './use_alerts_by_status';
|
||||
import { useAlertsByStatus } from './use_alerts_by_status';
|
||||
|
||||
const dateNow = new Date('2022-04-08T12:00:00.000Z').valueOf();
|
||||
|
@ -43,7 +42,7 @@ jest.mock('../../../../common/containers/use_global_time', () => {
|
|||
|
||||
// helper function to render the hook
|
||||
const renderUseAlertsByStatus = (props: Partial<UseAlertsByStatusProps> = {}) =>
|
||||
renderHook<PropsWithChildren<UseAlertsByStatusProps>, ReturnType<UseAlertsByStatus>>(
|
||||
renderHook(
|
||||
() =>
|
||||
useAlertsByStatus({
|
||||
queryId: 'test',
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useVisualizationResponse } from '../../../../common/components/visualization_actions/use_visualization_response';
|
||||
import {
|
||||
acknowledgedAlertsVisualizationId,
|
||||
|
|
|
@ -5,12 +5,10 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import type { PropsWithChildren } from 'react';
|
||||
import { renderHook, act } from '@testing-library/react-hooks';
|
||||
import { waitFor, renderHook } from '@testing-library/react';
|
||||
import { mockCasesContract } from '@kbn/cases-plugin/public/mocks';
|
||||
import { useKibana } from '../../../../common/lib/kibana';
|
||||
import { TestProviders } from '../../../../common/mock';
|
||||
import type { UseCasesByStatusProps, UseCasesByStatusResults } from './use_cases_by_status';
|
||||
import { useCasesByStatus } from './use_cases_by_status';
|
||||
|
||||
const dateNow = new Date('2022-04-08T12:00:00.000Z').valueOf();
|
||||
|
@ -40,14 +38,6 @@ mockGetCasesMetrics.mockResolvedValue({
|
|||
},
|
||||
});
|
||||
|
||||
mockGetCasesMetrics.mockResolvedValueOnce({
|
||||
status: {
|
||||
open: 0,
|
||||
inProgress: 0,
|
||||
closed: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const mockUseKibana = {
|
||||
services: {
|
||||
cases: {
|
||||
|
@ -67,81 +57,88 @@ describe('useCasesByStatus', () => {
|
|||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
test('init', () => {
|
||||
const { result } = renderHook<
|
||||
PropsWithChildren<UseCasesByStatusProps>,
|
||||
UseCasesByStatusResults
|
||||
>(() => useCasesByStatus({}), {
|
||||
test('init', async () => {
|
||||
mockGetCasesMetrics.mockResolvedValueOnce({
|
||||
status: {
|
||||
open: 0,
|
||||
inProgress: 0,
|
||||
closed: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useCasesByStatus({}), {
|
||||
wrapper: TestProviders,
|
||||
});
|
||||
expect(result.current).toEqual({
|
||||
closed: 0,
|
||||
inProgress: 0,
|
||||
isLoading: true,
|
||||
open: 0,
|
||||
totalCounts: 0,
|
||||
updatedAt: dateNow,
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toEqual({
|
||||
closed: 0,
|
||||
inProgress: 0,
|
||||
isLoading: true,
|
||||
open: 0,
|
||||
totalCounts: 0,
|
||||
updatedAt: dateNow,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('fetch data', async () => {
|
||||
const { result, waitForNextUpdate } = renderHook<
|
||||
PropsWithChildren<UseCasesByStatusProps>,
|
||||
UseCasesByStatusResults
|
||||
>(() => useCasesByStatus({ skip: false }), {
|
||||
const { result } = renderHook(() => useCasesByStatus({ skip: false }), {
|
||||
wrapper: TestProviders,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
expect(result.current).toEqual({
|
||||
closed: 3,
|
||||
inProgress: 2,
|
||||
isLoading: false,
|
||||
open: 1,
|
||||
totalCounts: 6,
|
||||
updatedAt: dateNow,
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(result.current).toEqual({
|
||||
closed: 3,
|
||||
inProgress: 2,
|
||||
isLoading: false,
|
||||
open: 1,
|
||||
totalCounts: 6,
|
||||
updatedAt: dateNow,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('it should call setQuery when fetching', async () => {
|
||||
const { waitForNextUpdate } = renderHook<
|
||||
PropsWithChildren<UseCasesByStatusProps>,
|
||||
UseCasesByStatusResults
|
||||
>(() => useCasesByStatus({ skip: false }), {
|
||||
renderHook(() => useCasesByStatus({ skip: false }), {
|
||||
wrapper: TestProviders,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
expect(mockSetQuery).toHaveBeenCalled();
|
||||
await waitFor(() => expect(mockSetQuery).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
test('it should call deleteQuery when unmounting', async () => {
|
||||
const { waitForNextUpdate, unmount } = renderHook<
|
||||
PropsWithChildren<UseCasesByStatusProps>,
|
||||
UseCasesByStatusResults
|
||||
>(() => useCasesByStatus({ skip: false }), {
|
||||
// muting setState warning that happens on unmount
|
||||
// because it's a noop and going to be removed
|
||||
// in the next version of React
|
||||
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const { unmount } = renderHook(() => useCasesByStatus({ skip: false }), {
|
||||
wrapper: TestProviders,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
|
||||
unmount();
|
||||
|
||||
expect(mockDeleteQuery).toHaveBeenCalled();
|
||||
waitFor(() => {
|
||||
expect(mockDeleteQuery).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
consoleError.mockRestore();
|
||||
});
|
||||
|
||||
test('skip', async () => {
|
||||
const abortSpy = jest.spyOn(AbortController.prototype, 'abort');
|
||||
const localProps = { skip: false };
|
||||
|
||||
const { rerender, waitForNextUpdate } = renderHook<
|
||||
PropsWithChildren<UseCasesByStatusProps>,
|
||||
UseCasesByStatusResults
|
||||
>(() => useCasesByStatus(localProps), {
|
||||
const { rerender } = renderHook(() => useCasesByStatus(localProps), {
|
||||
wrapper: TestProviders,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
|
||||
localProps.skip = true;
|
||||
act(() => rerender());
|
||||
act(() => rerender());
|
||||
expect(abortSpy).toHaveBeenCalledTimes(2);
|
||||
|
||||
rerender();
|
||||
rerender();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(abortSpy).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { waitFor, renderHook } from '@testing-library/react';
|
||||
|
||||
import { mockCasesResult, parsedCasesItems } from './mock_data';
|
||||
import { useCaseItems } from './use_case_items';
|
||||
|
@ -32,6 +32,7 @@ const mockKibana = {
|
|||
},
|
||||
},
|
||||
};
|
||||
|
||||
jest.mock('../../../../common/lib/kibana', () => ({
|
||||
useKibana: () => mockKibana,
|
||||
}));
|
||||
|
@ -51,7 +52,7 @@ jest.mock('../../../../common/containers/use_global_time', () => {
|
|||
});
|
||||
|
||||
const renderUseCaseItems = (overrides: Partial<UseCaseItemsProps> = {}) =>
|
||||
renderHook<UseCaseItems, ReturnType<UseCaseItems>>(() =>
|
||||
renderHook<ReturnType<UseCaseItems>, UseCaseItems>(() =>
|
||||
useCaseItems({ skip: false, ...overrides })
|
||||
);
|
||||
|
||||
|
@ -63,59 +64,55 @@ describe('useCaseItems', () => {
|
|||
});
|
||||
|
||||
it('should return default values', async () => {
|
||||
const { result, waitForNextUpdate } = renderUseCaseItems();
|
||||
const { result } = renderUseCaseItems();
|
||||
|
||||
await waitForNextUpdate();
|
||||
await waitFor(() => {
|
||||
expect(result.current).toEqual({
|
||||
items: [],
|
||||
isLoading: false,
|
||||
updatedAt: dateNow,
|
||||
});
|
||||
|
||||
expect(result.current).toEqual({
|
||||
items: [],
|
||||
isLoading: false,
|
||||
updatedAt: dateNow,
|
||||
});
|
||||
|
||||
expect(mockCasesApi).toBeCalledWith({
|
||||
from: '2020-07-07T08:20:18.966Z',
|
||||
to: '2020-07-08T08:20:18.966Z',
|
||||
owner: 'securitySolution',
|
||||
sortField: 'createdAt',
|
||||
sortOrder: 'desc',
|
||||
page: 1,
|
||||
perPage: 4,
|
||||
expect(mockCasesApi).toBeCalledWith({
|
||||
from: '2020-07-07T08:20:18.966Z',
|
||||
to: '2020-07-08T08:20:18.966Z',
|
||||
owner: 'securitySolution',
|
||||
sortField: 'createdAt',
|
||||
sortOrder: 'desc',
|
||||
page: 1,
|
||||
perPage: 4,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('should return parsed items', async () => {
|
||||
mockCasesApi.mockReturnValue(mockCasesResult);
|
||||
const { result, waitForNextUpdate } = renderUseCaseItems();
|
||||
const { result } = renderUseCaseItems();
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(result.current).toEqual({
|
||||
items: parsedCasesItems,
|
||||
isLoading: false,
|
||||
updatedAt: dateNow,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
items: parsedCasesItems,
|
||||
isLoading: false,
|
||||
updatedAt: dateNow,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test('it should call setQuery when fetching', async () => {
|
||||
mockCasesApi.mockReturnValue(mockCasesResult);
|
||||
const { waitForNextUpdate } = renderUseCaseItems();
|
||||
renderUseCaseItems();
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(mockSetQuery).toHaveBeenCalled();
|
||||
await waitFor(() => expect(mockSetQuery).toHaveBeenCalled());
|
||||
});
|
||||
|
||||
test('it should call deleteQuery when unmounting', async () => {
|
||||
const { waitForNextUpdate, unmount } = renderUseCaseItems();
|
||||
const { unmount } = renderUseCaseItems();
|
||||
|
||||
await waitForNextUpdate();
|
||||
unmount();
|
||||
|
||||
act(() => {
|
||||
unmount();
|
||||
await waitFor(() => {
|
||||
expect(mockDeleteQuery).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
expect(mockDeleteQuery).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return new updatedAt', async () => {
|
||||
|
@ -124,15 +121,15 @@ describe('useCaseItems', () => {
|
|||
mockDateNow.mockReturnValueOnce(dateNow);
|
||||
mockCasesApi.mockReturnValue(mockCasesResult);
|
||||
|
||||
const { result, waitForNextUpdate } = renderUseCaseItems();
|
||||
const { result } = renderUseCaseItems();
|
||||
|
||||
await waitForNextUpdate();
|
||||
|
||||
expect(mockDateNow).toHaveBeenCalled();
|
||||
expect(result.current).toEqual({
|
||||
items: parsedCasesItems,
|
||||
isLoading: false,
|
||||
updatedAt: newDateNow,
|
||||
await waitFor(() => {
|
||||
expect(mockDateNow).toHaveBeenCalled();
|
||||
expect(result.current).toEqual({
|
||||
items: parsedCasesItems,
|
||||
isLoading: false,
|
||||
updatedAt: newDateNow,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { useDeepEqualSelector } from '../../../../common/hooks/use_selector';
|
||||
import { updateProviders } from '../../../../timelines/store/actions';
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import {
|
||||
mockQuery,
|
||||
|
@ -51,7 +51,7 @@ jest.mock('../../../../common/containers/use_global_time', () => {
|
|||
});
|
||||
|
||||
const renderUseHostAlertsItems = (overrides: Partial<UseHostAlertsItemsProps> = {}) =>
|
||||
renderHook<UseHostAlertsItemsProps, ReturnType<UseHostAlertsItems>>(() =>
|
||||
renderHook<ReturnType<UseHostAlertsItems>, UseHostAlertsItemsProps>(() =>
|
||||
useHostAlertsItems({
|
||||
skip: false,
|
||||
signalIndexName,
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { ALERTS_QUERY_NAMES } from '../../../../detections/containers/detection_engine/alerts/constants';
|
||||
|
||||
import {
|
||||
|
@ -49,7 +49,7 @@ jest.mock('../../../../common/containers/use_global_time', () => {
|
|||
|
||||
// helper function to render the hook
|
||||
const renderUseRuleAlertsItems = (props: Partial<UseRuleAlertsItemsProps> = {}) =>
|
||||
renderHook<UseRuleAlertsItemsProps, ReturnType<UseRuleAlertsItems>>(() =>
|
||||
renderHook<ReturnType<UseRuleAlertsItems>, UseRuleAlertsItemsProps>(() =>
|
||||
useRuleAlertsItems({
|
||||
queryId: 'test',
|
||||
signalIndexName: 'signal-alerts',
|
||||
|
|
|
@ -8,7 +8,7 @@
|
|||
import React from 'react';
|
||||
import type { UseCasesMttr } from './use_cases_mttr';
|
||||
import { useCasesMttr } from './use_cases_mttr';
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { act, waitFor, renderHook } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../../common/mock';
|
||||
import { useKibana as useKibanaMock } from '../../../../../common/lib/kibana/__mocks__';
|
||||
import * as i18n from '../translations';
|
||||
|
@ -53,12 +53,13 @@ describe('useCasesMttr', () => {
|
|||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('loads initial state', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toEqual({
|
||||
stat: '-',
|
||||
isLoading: true,
|
||||
|
@ -71,16 +72,15 @@ describe('useCasesMttr', () => {
|
|||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('finds positive percentage change', async () => {
|
||||
useKibanaMock().services.cases.api.cases.getCasesMetrics = mockGetCasesMetrics
|
||||
.mockReturnValueOnce({ mttr: 10000 })
|
||||
.mockReturnValue({ mttr: 5000 });
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '2h',
|
||||
isLoading: false,
|
||||
|
@ -95,19 +95,17 @@ describe('useCasesMttr', () => {
|
|||
}),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('finds negative percentage change', async () => {
|
||||
useKibanaMock().services.cases.api.cases.getCasesMetrics = mockGetCasesMetrics
|
||||
.mockReturnValueOnce({ mttr: 5000 })
|
||||
.mockReturnValue({ mttr: 10000 });
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '1h',
|
||||
isLoading: false,
|
||||
|
@ -122,19 +120,17 @@ describe('useCasesMttr', () => {
|
|||
}),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('finds zero percentage change', async () => {
|
||||
useKibanaMock().services.cases.api.cases.getCasesMetrics = mockGetCasesMetrics.mockReturnValue({
|
||||
mttr: 10000,
|
||||
});
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '2h',
|
||||
isLoading: false,
|
||||
|
@ -144,19 +140,17 @@ describe('useCasesMttr', () => {
|
|||
note: i18n.NO_CHANGE('case resolution time'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('handles null mttr - current time range', async () => {
|
||||
useKibanaMock().services.cases.api.cases.getCasesMetrics = mockGetCasesMetrics
|
||||
.mockReturnValueOnce({ mttr: null })
|
||||
.mockReturnValue({ mttr: 10000 });
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '-',
|
||||
isLoading: false,
|
||||
|
@ -166,19 +160,17 @@ describe('useCasesMttr', () => {
|
|||
note: i18n.NO_DATA_CURRENT('case'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('handles null mttr - compare time range', async () => {
|
||||
useKibanaMock().services.cases.api.cases.getCasesMetrics = mockGetCasesMetrics
|
||||
.mockReturnValueOnce({ mttr: 10000 })
|
||||
.mockReturnValue({ mttr: null });
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCasesMttr(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '2h',
|
||||
isLoading: false,
|
||||
|
@ -188,8 +180,8 @@ describe('useCasesMttr', () => {
|
|||
note: i18n.NO_DATA_COMPARE('case'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('handles null mttr - current & compare time range', async () => {
|
||||
useKibanaMock().services.cases.api.cases.getCasesMetrics = mockGetCasesMetrics
|
||||
|
@ -198,13 +190,11 @@ describe('useCasesMttr', () => {
|
|||
.mockReturnValue({
|
||||
mttr: null,
|
||||
});
|
||||
await act(async () => {
|
||||
let ourProps = props;
|
||||
const { result, rerender, waitForNextUpdate } = renderHook(() => useCasesMttr(ourProps), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
let ourProps = props;
|
||||
const { result, rerender } = renderHook(() => useCasesMttr(ourProps), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '2h',
|
||||
isLoading: false,
|
||||
|
@ -214,14 +204,16 @@ describe('useCasesMttr', () => {
|
|||
note: i18n.NO_CHANGE('case resolution time'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
ourProps = {
|
||||
...props,
|
||||
from: '2020-07-08T08:20:18.966Z',
|
||||
to: '2020-07-09T08:20:18.966Z',
|
||||
};
|
||||
rerender();
|
||||
await waitForNextUpdate();
|
||||
})
|
||||
);
|
||||
|
||||
ourProps = {
|
||||
...props,
|
||||
from: '2020-07-08T08:20:18.966Z',
|
||||
to: '2020-07-09T08:20:18.966Z',
|
||||
};
|
||||
rerender();
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '-',
|
||||
isLoading: false,
|
||||
|
@ -231,8 +223,8 @@ describe('useCasesMttr', () => {
|
|||
note: i18n.NO_DATA('case'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('handles undefined mttr - current & compare time range', async () => {
|
||||
useKibanaMock().services.cases.api.cases.getCasesMetrics = mockGetCasesMetrics
|
||||
|
@ -241,13 +233,12 @@ describe('useCasesMttr', () => {
|
|||
.mockReturnValue({
|
||||
mttr: undefined,
|
||||
});
|
||||
await act(async () => {
|
||||
let ourProps = props;
|
||||
const { result, rerender, waitForNextUpdate } = renderHook(() => useCasesMttr(ourProps), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
let ourProps = props;
|
||||
const { result, rerender } = renderHook(() => useCasesMttr(ourProps), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '2h',
|
||||
isLoading: false,
|
||||
|
@ -257,15 +248,21 @@ describe('useCasesMttr', () => {
|
|||
note: i18n.NO_CHANGE('case resolution time'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
ourProps = {
|
||||
...props,
|
||||
from: '2020-07-08T08:20:18.966Z',
|
||||
to: '2020-07-09T08:20:18.966Z',
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
ourProps = {
|
||||
...props,
|
||||
from: '2020-07-08T08:20:18.966Z',
|
||||
to: '2020-07-09T08:20:18.966Z',
|
||||
};
|
||||
|
||||
act(() => {
|
||||
rerender();
|
||||
rerender();
|
||||
await waitForNextUpdate();
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '-',
|
||||
isLoading: false,
|
||||
|
@ -275,7 +272,7 @@ describe('useCasesMttr', () => {
|
|||
note: i18n.NO_DATA('case'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -8,7 +8,7 @@
|
|||
import React from 'react';
|
||||
import type { UseCriticalAlerts } from './use_critical_alerts';
|
||||
import { useCriticalAlerts } from './use_critical_alerts';
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { waitFor, renderHook } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../../../common/mock';
|
||||
import * as i18n from '../translations';
|
||||
import { useQueryAlerts } from '../../../../../detections/containers/detection_engine/alerts/use_query';
|
||||
|
@ -66,14 +66,20 @@ describe('useCriticalAlerts', () => {
|
|||
jest.clearAllMocks();
|
||||
});
|
||||
it('loads initial state', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
// mock useQuery into state before data fetch
|
||||
mockUseQueryAlerts.mockReturnValue({
|
||||
...basicReturn,
|
||||
data: null,
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toEqual({
|
||||
stat: '-',
|
||||
isLoading: true,
|
||||
isLoading: false,
|
||||
percentage: {
|
||||
percent: null,
|
||||
color: 'hollow',
|
||||
|
@ -95,12 +101,10 @@ describe('useCriticalAlerts', () => {
|
|||
...basicReturn,
|
||||
}
|
||||
);
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '100',
|
||||
isLoading: false,
|
||||
|
@ -115,8 +119,8 @@ describe('useCriticalAlerts', () => {
|
|||
}),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('finds negative percentage change', async () => {
|
||||
mockUseQueryAlerts.mockImplementation((args) =>
|
||||
|
@ -130,12 +134,10 @@ describe('useCriticalAlerts', () => {
|
|||
...basicReturn,
|
||||
}
|
||||
);
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '50',
|
||||
isLoading: false,
|
||||
|
@ -150,20 +152,18 @@ describe('useCriticalAlerts', () => {
|
|||
}),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('finds zero percentage change', async () => {
|
||||
mockUseQueryAlerts.mockImplementation((args) => ({
|
||||
data: { aggregations: { open: { critical: { doc_count: 100 } } } },
|
||||
...basicReturn,
|
||||
}));
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '100',
|
||||
isLoading: false,
|
||||
|
@ -173,8 +173,8 @@ describe('useCriticalAlerts', () => {
|
|||
note: i18n.NO_CHANGE('open critical alert count'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('handles null data - current time range', async () => {
|
||||
mockUseQueryAlerts.mockImplementation((args) =>
|
||||
|
@ -188,12 +188,10 @@ describe('useCriticalAlerts', () => {
|
|||
...basicReturn,
|
||||
}
|
||||
);
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '-',
|
||||
isLoading: false,
|
||||
|
@ -203,8 +201,8 @@ describe('useCriticalAlerts', () => {
|
|||
note: i18n.NO_DATA_CURRENT('alerts'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('handles null data - compare time range', async () => {
|
||||
mockUseQueryAlerts.mockImplementation((args) =>
|
||||
|
@ -218,12 +216,10 @@ describe('useCriticalAlerts', () => {
|
|||
...basicReturn,
|
||||
}
|
||||
);
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(() => useCriticalAlerts(props), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '100',
|
||||
isLoading: false,
|
||||
|
@ -233,8 +229,8 @@ describe('useCriticalAlerts', () => {
|
|||
note: i18n.NO_DATA_COMPARE('alerts'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('handles null data - current & compare time range', async () => {
|
||||
mockUseQueryAlerts.mockImplementation((args) =>
|
||||
|
@ -249,16 +245,12 @@ describe('useCriticalAlerts', () => {
|
|||
...basicReturn,
|
||||
}
|
||||
);
|
||||
await act(async () => {
|
||||
let ourProps = props;
|
||||
const { result, rerender, waitForNextUpdate } = renderHook(
|
||||
() => useCriticalAlerts(ourProps),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
let ourProps = props;
|
||||
const { result, rerender } = renderHook(() => useCriticalAlerts(ourProps), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '100',
|
||||
isLoading: false,
|
||||
|
@ -268,16 +260,18 @@ describe('useCriticalAlerts', () => {
|
|||
note: i18n.NO_CHANGE('open critical alert count'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
ourProps = {
|
||||
...props,
|
||||
from: '2020-09-08T08:20:18.966Z',
|
||||
to: '2020-09-09T08:20:18.966Z',
|
||||
fromCompare: '2020-09-07T08:20:18.966Z',
|
||||
toCompare: '2020-09-08T08:20:18.966Z',
|
||||
};
|
||||
rerender();
|
||||
await waitForNextUpdate();
|
||||
})
|
||||
);
|
||||
|
||||
ourProps = {
|
||||
...props,
|
||||
from: '2020-09-08T08:20:18.966Z',
|
||||
to: '2020-09-09T08:20:18.966Z',
|
||||
fromCompare: '2020-09-07T08:20:18.966Z',
|
||||
toCompare: '2020-09-08T08:20:18.966Z',
|
||||
};
|
||||
rerender();
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '-',
|
||||
isLoading: false,
|
||||
|
@ -287,8 +281,8 @@ describe('useCriticalAlerts', () => {
|
|||
note: i18n.NO_DATA('alerts'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
it('handles undefined data - current & compare time range', async () => {
|
||||
mockUseQueryAlerts.mockImplementation((args) =>
|
||||
|
@ -303,16 +297,11 @@ describe('useCriticalAlerts', () => {
|
|||
...basicReturn,
|
||||
}
|
||||
);
|
||||
await act(async () => {
|
||||
let ourProps = props;
|
||||
const { result, rerender, waitForNextUpdate } = renderHook(
|
||||
() => useCriticalAlerts(ourProps),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
await waitForNextUpdate();
|
||||
let ourProps = props;
|
||||
const { result, rerender } = renderHook(() => useCriticalAlerts(ourProps), {
|
||||
wrapper: wrapperContainer,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '100',
|
||||
isLoading: false,
|
||||
|
@ -322,16 +311,17 @@ describe('useCriticalAlerts', () => {
|
|||
note: i18n.NO_CHANGE('open critical alert count'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
ourProps = {
|
||||
...props,
|
||||
from: '2020-09-08T08:20:18.966Z',
|
||||
to: '2020-09-09T08:20:18.966Z',
|
||||
fromCompare: '2020-09-07T08:20:18.966Z',
|
||||
toCompare: '2020-09-08T08:20:18.966Z',
|
||||
};
|
||||
rerender();
|
||||
await waitForNextUpdate();
|
||||
})
|
||||
);
|
||||
ourProps = {
|
||||
...props,
|
||||
from: '2020-09-08T08:20:18.966Z',
|
||||
to: '2020-09-09T08:20:18.966Z',
|
||||
fromCompare: '2020-09-07T08:20:18.966Z',
|
||||
toCompare: '2020-09-08T08:20:18.966Z',
|
||||
};
|
||||
rerender();
|
||||
await waitFor(() =>
|
||||
expect(result.current).toEqual({
|
||||
stat: '-',
|
||||
isLoading: false,
|
||||
|
@ -341,7 +331,7 @@ describe('useCriticalAlerts', () => {
|
|||
note: i18n.NO_DATA('alerts'),
|
||||
},
|
||||
...basicData,
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
@ -6,8 +6,9 @@
|
|||
*/
|
||||
|
||||
import React from 'react';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
|
||||
import { useSocTrends } from './use_soc_trends';
|
||||
import { act, renderHook } from '@testing-library/react-hooks';
|
||||
import { TestProviders } from '../../../../../common/mock';
|
||||
import { useGlobalTime } from '../../../../../common/containers/use_global_time';
|
||||
import * as i18n from '../translations';
|
||||
|
@ -42,14 +43,13 @@ describe('useSocTrends', () => {
|
|||
jest.clearAllMocks();
|
||||
});
|
||||
it('loads initial state', async () => {
|
||||
await act(async () => {
|
||||
const { result, waitForNextUpdate } = renderHook(
|
||||
() => useSocTrends({ skip: false, signalIndexName: '.alerts-default' }),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitForNextUpdate();
|
||||
const { result } = renderHook(
|
||||
() => useSocTrends({ skip: false, signalIndexName: '.alerts-default' }),
|
||||
{
|
||||
wrapper: wrapperContainer,
|
||||
}
|
||||
);
|
||||
await waitFor(() => {
|
||||
expect(result.current).toEqual({
|
||||
stats: [
|
||||
{
|
||||
|
|
|
@ -5,7 +5,7 @@
|
|||
* 2.0.
|
||||
*/
|
||||
|
||||
import { renderHook } from '@testing-library/react-hooks';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import {
|
||||
mockQuery,
|
||||
|
@ -14,7 +14,7 @@ import {
|
|||
} from './mock_data';
|
||||
import { useUserAlertsItems } from './use_user_alerts_items';
|
||||
|
||||
import type { UseUserAlertsItems, UseUserAlertsItemsProps } from './use_user_alerts_items';
|
||||
import type { UseUserAlertsItemsProps } from './use_user_alerts_items';
|
||||
|
||||
const signalIndexName = 'signal-alerts';
|
||||
|
||||
|
@ -50,7 +50,7 @@ jest.mock('../../../../common/containers/use_global_time', () => {
|
|||
});
|
||||
|
||||
const renderUseUserAlertsItems = (overrides: Partial<UseUserAlertsItemsProps> = {}) =>
|
||||
renderHook<UseUserAlertsItemsProps, ReturnType<UseUserAlertsItems>>(() =>
|
||||
renderHook(() =>
|
||||
useUserAlertsItems({
|
||||
skip: false,
|
||||
signalIndexName,
|
||||
|
|
|
@ -4,7 +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';
|
||||
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../common/mock';
|
||||
import { useHostOverview } from '.';
|
||||
import { useSearchStrategy } from '../../../common/containers/use_search_strategy';
|
||||
|
|
|
@ -4,7 +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';
|
||||
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { TestProviders } from '../../../common/mock';
|
||||
import { useNetworkOverview } from '.';
|
||||
import { useSearchStrategy } from '../../../common/containers/use_search_strategy';
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue