Skip to content

Commit

Permalink
unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
angorayc committed Jan 8, 2024
1 parent dc354b8 commit 98b200c
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 137 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import { TestProviders } from '../../../../common/mock';
import type { RulePreviewProps } from '.';
import { RulePreview, REASONABLE_INVOCATION_COUNT } from '.';
import { usePreviewRoute } from './use_preview_route';
import { usePreviewHistogram } from './use_preview_histogram';
import { DataSourceType } from '../../../../detections/pages/detection_engine/rules/types';
import {
getStepScheduleDefaultValue,
Expand All @@ -26,7 +25,6 @@ import { usePreviewInvocationCount } from './use_preview_invocation_count';

jest.mock('../../../../common/lib/kibana');
jest.mock('./use_preview_route');
jest.mock('./use_preview_histogram');
jest.mock('../../../../common/containers/use_global_time', () => ({
useGlobalTime: jest.fn().mockReturnValue({
from: '2020-07-07T08:20:18.966Z',
Expand Down Expand Up @@ -88,17 +86,6 @@ const defaultProps: RulePreviewProps = {

describe('PreviewQuery', () => {
beforeEach(() => {
(usePreviewHistogram as jest.Mock).mockReturnValue([
false,
{
inspect: { dsl: [], response: [] },
totalCount: 1,
refetch: jest.fn(),
data: [],
buckets: [],
},
]);

(usePreviewRoute as jest.Mock).mockReturnValue({
hasNoiseWarning: false,
addNoiseWarning: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,18 @@ import {
SUB_PLUGINS_REDUCER,
TestProviders,
} from '../../../../common/mock';
import { usePreviewHistogram } from './use_preview_histogram';
import { VisualizationEmbeddable } from '../../../../common/components/visualization_actions/visualization_embeddable';
import { useVisualizationResponse } from '../../../../common/components/visualization_actions/use_visualization_response';

import { PreviewHistogram } from './preview_histogram';
import { ALL_VALUES_ZEROS_TITLE } from '../../../../common/components/charts/translation';
import { useTimelineEvents } from '../../../../common/components/events_viewer/use_timelines_events';
import { TableId } from '@kbn/securitysolution-data-table';
import { createStore } from '../../../../common/store';
import { mockEventViewerResponse } from '../../../../common/components/events_viewer/mock';
import type { ReactWrapper } from 'enzyme';
import { mount } from 'enzyme';
import type { UseFieldBrowserOptionsProps } from '../../../../timelines/components/fields_browser';
import type { TransformColumnsProps } from '../../../../common/components/control_columns';
import { useIsExperimentalFeatureEnabled } from '../../../../common/hooks/use_experimental_features';
import type { ExperimentalFeatures } from '../../../../../common/experimental_features';
import { allowedExperimentalValues } from '../../../../../common/experimental_features';
import { INSPECT_ACTION } from '../../../../common/components/visualization_actions/use_actions';

jest.mock('../../../../common/components/control_columns', () => ({
transformControlColumns: (props: TransformColumnsProps) => [],
Expand All @@ -46,17 +43,17 @@ jest.mock('../../../../common/components/control_columns', () => ({
}));
jest.mock('../../../../common/lib/kibana');
jest.mock('../../../../common/containers/use_global_time');
jest.mock('./use_preview_histogram');
jest.mock('../../../../common/utils/normalize_time_range');
jest.mock('../../../../common/components/events_viewer/use_timelines_events');
jest.mock('../../../../common/components/visualization_actions/visualization_embeddable');
jest.mock('../../../../common/components/visualization_actions/use_visualization_response', () => ({
useVisualizationResponse: jest.fn(),
}));

jest.mock('../../../../common/hooks/use_experimental_features', () => ({
useIsExperimentalFeatureEnabled: jest.fn(),
}));
const mockUseIsExperimentalFeatureEnabled = useIsExperimentalFeatureEnabled as jest.Mock;
const getMockUseIsExperimentalFeatureEnabled =
(mockMapping?: Partial<ExperimentalFeatures>) => (flag: keyof typeof allowedExperimentalValues) =>
mockMapping ? mockMapping?.[flag] : allowedExperimentalValues?.[flag];
const mockVisualizationEmbeddable = VisualizationEmbeddable as unknown as jest.Mock;

const mockUseFieldBrowserOptions = jest.fn();
jest.mock('../../../../timelines/components/fields_browser', () => ({
Expand All @@ -82,9 +79,6 @@ describe('PreviewHistogram', () => {
const mockSetQuery = jest.fn();

beforeEach(() => {
mockUseIsExperimentalFeatureEnabled.mockImplementation(
getMockUseIsExperimentalFeatureEnabled({ alertsPreviewChartEmbeddablesEnabled: false })
);
(useGlobalTime as jest.Mock).mockReturnValue({
from: '2020-07-07T08:20:18.966Z',
isInitializing: false,
Expand Down Expand Up @@ -116,26 +110,14 @@ describe('PreviewHistogram', () => {
jest.clearAllMocks();
});

describe('when there is no data', () => {
(usePreviewHistogram as jest.Mock).mockReturnValue([
false,
{
inspect: { dsl: [], response: [] },
totalCount: 1,
refetch: jest.fn(),
data: [],
buckets: [],
},
]);
describe('PreviewHistogram', () => {
test('should render Lens embeddable', () => {
(useVisualizationResponse as jest.Mock).mockReturnValue({
loading: false,
requests: [],
responses: [{ hits: { total: 1 } }],
});

test('it renders an empty histogram and table', async () => {
(useTimelineEvents as jest.Mock).mockReturnValue([
false,
{
...mockEventViewerResponse,
totalCount: 1,
},
]);
const wrapper = mount(
<TestProviders store={store}>
<PreviewHistogram
Expand All @@ -148,27 +130,41 @@ describe('PreviewHistogram', () => {
/>
</TestProviders>
);
expect(wrapper.findWhere((node) => node.text() === '1 alert').exists()).toBeTruthy();
expect(
wrapper.findWhere((node) => node.text() === ALL_VALUES_ZEROS_TITLE).exists()
).toBeTruthy();

expect(wrapper.find('[data-test-subj="visualization-embeddable"]').exists()).toBeTruthy();
});
});

describe('when there is data', () => {
test('it renders loader when isLoading is true', () => {
(usePreviewHistogram as jest.Mock).mockReturnValue([
true,
{
inspect: { dsl: [], response: [] },
totalCount: 1,
refetch: jest.fn(),
data: [],
buckets: [],
},
]);
test('should render inspect action', () => {
(useVisualizationResponse as jest.Mock).mockReturnValue({
loading: false,
requests: [],
responses: [{ hits: { total: 1 } }],
});

const wrapper = mount(
mount(
<TestProviders store={store}>
<PreviewHistogram
addNoiseWarning={jest.fn()}
timeframeOptions={getLastMonthTimeframe()}
previewId={'test-preview-id'}
spaceId={'default'}
ruleType={'query'}
indexPattern={getMockIndexPattern()}
/>
</TestProviders>
);

expect(mockVisualizationEmbeddable.mock.calls[0][0].withActions).toEqual(INSPECT_ACTION);
});

test('should show chart legend when if it is not EQL rule', () => {
(useVisualizationResponse as jest.Mock).mockReturnValue({
loading: false,
requests: [],
responses: [{ hits: { total: 1 } }],
});

mount(
<TestProviders store={store}>
<PreviewHistogram
addNoiseWarning={jest.fn()}
Expand All @@ -181,7 +177,7 @@ describe('PreviewHistogram', () => {
</TestProviders>
);

expect(wrapper.find(`[data-test-subj="preview-histogram-loading"]`).exists()).toBeTruthy();
expect(mockVisualizationEmbeddable.mock.calls[0][0].extraOptions.showLegend).toBeTruthy();
});
});

Expand All @@ -197,36 +193,13 @@ describe('PreviewHistogram', () => {
totalCount: 0,
},
]);
const usePreviewHistogramMock = usePreviewHistogram as jest.Mock;
usePreviewHistogramMock.mockReturnValue([
true,
{
inspect: { dsl: [], response: [] },
totalCount: 1,
refetch: jest.fn(),
data: [],
buckets: [],
},
]);

usePreviewHistogramMock.mockImplementation(
({ startDate, endDate }: { startDate: string; endDate: string }) => {
expect(startDate).toEqual('2015-03-12T09:17:10.000Z');
expect(endDate).toEqual('2020-03-12T09:17:10.000Z');
return [
true,
{
inspect: { dsl: [], response: [] },
totalCount: 1,
refetch: jest.fn(),
data: [],
buckets: [],
},
];
}
);
(useVisualizationResponse as jest.Mock).mockReturnValue({
loading: false,
requests: [],
responses: [{ hits: { total: 0 } }],
});

const wrapper = mount(
mount(
<TestProviders store={store}>
<PreviewHistogram
addNoiseWarning={jest.fn()}
Expand All @@ -244,49 +217,10 @@ describe('PreviewHistogram', () => {
</TestProviders>
);

expect(wrapper.find(`[data-test-subj="preview-histogram-loading"]`).exists()).toBeTruthy();
});
});

describe('when the alertsPreviewChartEmbeddablesEnabled experimental feature flag is enabled', () => {
let wrapper: ReactWrapper;
beforeEach(() => {
mockUseIsExperimentalFeatureEnabled.mockImplementation(
getMockUseIsExperimentalFeatureEnabled({
alertsPreviewChartEmbeddablesEnabled: true,
})
);

(usePreviewHistogram as jest.Mock).mockReturnValue([
false,
{
inspect: { dsl: [], response: [] },
totalCount: 1,
refetch: jest.fn(),
data: [],
buckets: [],
},
]);
wrapper = mount(
<TestProviders store={store}>
<PreviewHistogram
addNoiseWarning={jest.fn()}
previewId={'test-preview-id'}
spaceId={'default'}
ruleType={'query'}
indexPattern={getMockIndexPattern()}
timeframeOptions={getLastMonthTimeframe()}
/>
</TestProviders>
);
});

test('should not fetch preview data', () => {
expect((usePreviewHistogram as jest.Mock).mock.calls[0][0].skip).toEqual(true);
});

test('should render Lens embeddable', () => {
expect(wrapper.find('[data-test-subj="visualization-embeddable"]').exists()).toBeTruthy();
expect(mockVisualizationEmbeddable.mock.calls[0][0].timerange).toEqual({
from: moment(start, format).toISOString(),
to: moment(end, format).toISOString(),
});
});
});
});

0 comments on commit 98b200c

Please sign in to comment.