Skip to content

Commit

Permalink
fix maintenance window issue, add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
js-jankisalvi committed Sep 18, 2024
1 parent a29fa86 commit 5c0eb06
Show file tree
Hide file tree
Showing 4 changed files with 267 additions and 7 deletions.
128 changes: 128 additions & 0 deletions packages/kbn-alerts-ui-shared/src/alerts_search_bar/index.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/

import React from 'react';
import { render, screen } from '@testing-library/react';
import { dataPluginMock } from '@kbn/data-plugin/public/mocks';
import { httpServiceMock, notificationServiceMock } from '@kbn/core/public/mocks';
import { Filter } from '@kbn/es-query';
import { useLoadRuleTypesQuery, useAlertsDataView, useRuleAADFields } from '../common/hooks';
import { AlertsSearchBar } from '.';

jest.mock('../common/hooks/use_load_rule_types_query');
jest.mock('../common/hooks/use_rule_aad_fields');
jest.mock('../common/hooks/use_alerts_data_view');

jest.mocked(useAlertsDataView).mockReturnValue({
isLoading: false,
dataView: {
title: '.alerts-*',
fields: [
{
name: 'event.action',
type: 'string',
aggregatable: true,
searchable: true,
},
],
},
});

jest.mocked(useLoadRuleTypesQuery).mockReturnValue({
ruleTypesState: {
isInitialLoad: false,
data: new Map(),
isLoading: false,
error: null,
},
authorizedToReadAnyRules: false,
hasAnyAuthorizedRuleType: false,
authorizedRuleTypes: [],
authorizedToCreateAnyRules: false,
isSuccess: false,
});

jest.mocked(useRuleAADFields).mockReturnValue({
aadFields: [],
loading: false,
});

const mockDataPlugin = dataPluginMock.createStartContract();
const unifiedSearchBarMock = jest.fn().mockImplementation((props) => (
<button
data-test-subj="querySubmitButton"
onClick={() => props.onQuerySubmit({ dateRange: { from: 'now', to: 'now' } })}
type="button"
>
{'Hello world'}
</button>
));
const httpMock = httpServiceMock.createStartContract();
const toastsMock = notificationServiceMock.createStartContract().toasts;

describe('AlertsSearchBar', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('renders correctly', () => {
render(
<AlertsSearchBar
rangeFrom="now/d"
rangeTo="now/d"
query=""
onQuerySubmit={jest.fn()}
initialFilters={[]}
onFiltersUpdated={jest.fn()}
appName={'test'}
dataService={mockDataPlugin}
featureIds={['observability', 'stackAlerts']}
unifiedSearchBar={unifiedSearchBarMock}
http={httpMock}
toasts={toastsMock}
/>
);
expect(screen.getByTestId('querySubmitButton')).toBeInTheDocument();
});

it('renders initial filters correctly', () => {
const filters = [
{
meta: {
negate: false,
alias: null,
disabled: false,
type: 'custom',
key: 'query',
},
query: { match_phrase: { 'host.name': 'testValue' } },
$state: { store: 'appState' },
},
] as Filter[];

render(
<AlertsSearchBar
rangeFrom="now/d"
rangeTo="now/d"
query=""
onQuerySubmit={jest.fn()}
initialFilters={filters}
onFiltersUpdated={jest.fn()}
appName={'test'}
dataService={mockDataPlugin}
featureIds={['observability', 'stackAlerts']}
unifiedSearchBar={unifiedSearchBarMock}
http={httpMock}
toasts={toastsMock}
/>
);

expect(mockDataPlugin.query.filterManager.addFilters).toHaveBeenCalledWith(filters);
});
});
8 changes: 2 additions & 6 deletions packages/kbn-alerts-ui-shared/src/alerts_search_bar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
*/

import { useCallback, useMemo, useEffect, useState } from 'react';
import { cloneDeep } from 'lodash';
import type { Query, TimeRange } from '@kbn/es-query';
import type { SuggestionsAbstraction } from '@kbn/unified-search-plugin/public/typeahead/suggestions_component';
import { AlertConsumers, ValidFeatureId } from '@kbn/rule-data-utils';
import { NO_INDEX_PATTERNS } from './constants';
import { SEARCH_BAR_PLACEHOLDER } from './translations';
import type { AlertsSearchBarProps, QueryLanguageType } from './types';
import { useLoadRuleTypesQuery, useAlertsDataView, useRuleAADFields } from '../common/hooks';
import { cloneDeep } from 'lodash';

const SA_ALERTS = { type: 'alerts', fields: {} } as SuggestionsAbstraction;

Expand Down Expand Up @@ -110,11 +110,6 @@ export const AlertsSearchBar = ({
let isFirstRender = true;

if (initialFilters?.length && isFirstRender) {
console.log('adding filter', {
initialFilters,
isFirstRender,
getFilters: dataService.query.filterManager.getFilters(),
});
dataService.query.filterManager.addFilters(cloneDeep(initialFilters));
}

Expand Down Expand Up @@ -152,6 +147,7 @@ export const AlertsSearchBar = ({
submitOnBlur,
onQueryChange: onSearchQueryChange,
suggestionsAbstraction: isSecurity ? undefined : SA_ALERTS,
filters: initialFilters,
});
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import React from 'react';
import { render, screen } from '@testing-library/react';
import { useAlertsDataView } from '@kbn/alerts-ui-shared/src/common/hooks/use_alerts_data_view';
import { dataPluginMock } from '@kbn/data-plugin/public/mocks';
import { Filter } from '@kbn/es-query';
import { NotificationsStart } from '@kbn/core-notifications-browser';
import { useLoadRuleTypesQuery } from '../../hooks/use_load_rule_types_query';
import { useRuleAADFields } from '../../hooks/use_rule_aad_fields';
import { AlertsSearchBar } from './alerts_search_bar';

const mockDataPlugin = dataPluginMock.createStartContract();
jest.mock('../../hooks/use_load_rule_types_query');
jest.mock('../../hooks/use_rule_aad_fields');
jest.mock('@kbn/alerts-ui-shared/src/common/hooks/use_alerts_data_view');
jest.mock('@kbn/kibana-react-plugin/public', () => {
const original = jest.requireActual('@kbn/kibana-react-plugin/public');
return {
useKibana: () => ({
services: {
...original.useKibana().services,
data: mockDataPlugin,
unifiedSearch: {
ui: {
SearchBar: jest.fn().mockImplementation((props) => (
<button
data-test-subj="querySubmitButton"
onClick={() => props.onQuerySubmit({ dateRange: { from: 'now', to: 'now' } })}
type="button"
>
{'Hello world'}
</button>
)),
},
},
notifications: { toasts: { addWarning: jest.fn() } } as unknown as NotificationsStart,
},
}),
};
});
jest.mocked(useAlertsDataView).mockReturnValue({
isLoading: false,
dataView: {
title: '.alerts-*',
fields: [
{
name: 'event.action',
type: 'string',
aggregatable: true,
searchable: true,
},
],
},
});

jest.mocked(useLoadRuleTypesQuery).mockReturnValue({
ruleTypesState: {
initialLoad: false,
data: new Map(),
isLoading: false,
error: undefined,
},
authorizedToReadAnyRules: false,
hasAnyAuthorizedRuleType: false,
authorizedRuleTypes: [],
authorizedToCreateAnyRules: false,
isSuccess: false,
});

jest.mocked(useRuleAADFields).mockReturnValue({
aadFields: [],
loading: false,
});

describe('AlertsSearchBar', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('renders correctly', () => {
render(
<AlertsSearchBar
rangeFrom="now/d"
rangeTo="now/d"
query=""
onQuerySubmit={jest.fn()}
initialFilters={[]}
onFiltersUpdated={jest.fn()}
onSavedQueryUpdated={jest.fn()}
onClearSavedQuery={jest.fn()}
appName={'test'}
featureIds={['observability', 'stackAlerts']}
/>
);
expect(screen.getByTestId('querySubmitButton')).toBeInTheDocument();
});

it('renders initial filters correctly', () => {
const filters = [
{
meta: {
negate: false,
alias: null,
disabled: false,
type: 'custom',
key: 'query',
},
query: { match_phrase: { 'host.name': 'testValue' } },
$state: { store: 'appState' },
},
] as Filter[];

render(
<AlertsSearchBar
rangeFrom="now/d"
rangeTo="now/d"
query=""
onQuerySubmit={jest.fn()}
initialFilters={filters}
onFiltersUpdated={jest.fn()}
onSavedQueryUpdated={jest.fn()}
onClearSavedQuery={jest.fn()}
appName={'test'}
featureIds={['observability', 'stackAlerts']}
/>
);

expect(mockDataPlugin.query.filterManager.addFilters).toHaveBeenCalledWith(filters);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ import { SuggestionsAbstraction } from '@kbn/unified-search-plugin/public/typeah
import { AlertConsumers, ValidFeatureId } from '@kbn/rule-data-utils';
import { EuiContextMenuPanelDescriptor, EuiContextMenuPanelItemDescriptor } from '@elastic/eui';
import { useAlertsDataView } from '@kbn/alerts-ui-shared/src/common/hooks/use_alerts_data_view';
import { cloneDeep } from 'lodash';
import { isQuickFiltersGroup, QuickFiltersMenuItem } from './quick_filters';
import { NO_INDEX_PATTERNS } from './constants';
import { SEARCH_BAR_PLACEHOLDER } from './translations';
import { AlertsSearchBarProps, QueryLanguageType } from './types';
import { TriggersAndActionsUiServices } from '../../..';
import { useRuleAADFields } from '../../hooks/use_rule_aad_fields';
import { useLoadRuleTypesQuery } from '../../hooks/use_load_rule_types_query';
import { cloneDeep } from 'lodash';

const SA_ALERTS = { type: 'alerts', fields: {} } as SuggestionsAbstraction;
const EMPTY_FEATURE_IDS: ValidFeatureId[] = [];
Expand Down

0 comments on commit 5c0eb06

Please sign in to comment.