Skip to content

Commit

Permalink
Expression component test WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
Zacqary committed Jun 18, 2020
1 parent bdf9b90 commit dd4eab4
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import { mountWithIntl, nextTick } from 'test_utils/enzyme_helpers';
import { actionTypeRegistryMock } from '../../../../../triggers_actions_ui/public/application/action_type_registry.mock';
import { alertTypeRegistryMock } from '../../../../../triggers_actions_ui/public/application/alert_type_registry.mock';
import { coreMock } from '../../../../../../../src/core/public/mocks';
import { AlertsContextValue } from '../../../../../triggers_actions_ui/public/application/context/alerts_context';
import { AlertContextMeta, MetricExpression } from '../types';
import { MetricsExplorerMetric } from '../../../../common/http_api/metrics_explorer';
import React from 'react';
import { Expressions, defaultExpression } from './expression';
import { act } from 'react-dom/test-utils';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { Comparator } from '../../../../server/lib/alerting/metric_threshold/types';
import { MetricsExplorerResponse } from '../../../../common/http_api';
import { validateMetricThreshold } from './validation';

describe('Expression', () => {
async function setup(currentOptions: {
metrics?: MetricsExplorerMetric[];
filterQuery?: string;
groupBy?: string;
}) {
const alertParams = {
criteria: [defaultExpression],
};

const mocks = coreMock.createSetup();
const [
{
application: { capabilities },
},
] = await mocks.getStartServices();

const context: AlertsContextValue<AlertContextMeta> = {
http: mocks.http,
toastNotifications: mocks.notifications.toasts,
actionTypeRegistry: actionTypeRegistryMock.create() as any,
alertTypeRegistry: alertTypeRegistryMock.create() as any,
docLinks: mocks.docLinks,
capabilities: {
...capabilities,
actions: {
delete: true,
save: true,
show: true,
},
},
metadata: {
currentOptions,
},
};

const validationResult = validateMetricThreshold([alertParams.criteria]);

const wrapper = mountWithIntl(
<Expressions
alertsContext={context}
alertInterval="1m"
alertParams={alertParams}
errors={validationResult.errors}
setAlertParams={(key, value) => Reflect.set(alertParams, key, value)}
setAlertProperty={() => {}}
/>
);

const update = async () =>
await act(async () => {
await nextTick();
wrapper.update();
});

await update();

return { wrapper, update, alertParams };
}

it('should prefill the alert using the context metadata', async () => {
const currentOptions = {
groupBy: 'host.hostname',
filterQuery: 'foo',
metrics: [{ aggregation: 'avg', field: 'system.load.1' }],
};
const { alertParams } = await setup(currentOptions);
expect(alertParams.groupBy).toBe('host.hostname');
expect(alertParams.filterQueryText).toBe('foo');
expect(alertParams.criteria).toEqual([
{
metric: 'system.load.1',
comparator: Comparator.GT,
threshold: [],
timeSize,
timeUnit,
aggType: 'avg',
},
]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* you may not use this file except in compliance with the Elastic License.
*/

import { debounce, pick } from 'lodash';
import { debounce, pick, omit } from 'lodash';
import * as rt from 'io-ts';
import { HttpSetup } from 'src/core/public';
import React, { ChangeEvent, useCallback, useMemo, useEffect, useState } from 'react';
Expand Down Expand Up @@ -71,6 +71,7 @@ const defaultExpression = {
timeSize: 1,
timeUnit: 'm',
} as MetricExpression;
export { defaultExpression };

async function getAlertPreview({
fetch,
Expand Down Expand Up @@ -481,7 +482,7 @@ export const Expressions: React.FC<Props> = (props) => {
id="selectPreviewLookbackInterval"
value={previewLookbackInterval}
onChange={onSelectPreviewLookbackInterval}
options={previewOptions}
options={previewDOMOptions}
/>
</EuiFlexItem>
<EuiFlexItem grow={false}>
Expand Down Expand Up @@ -642,6 +643,7 @@ const previewOptions = [
}),
},
];
const previewDOMOptions = previewOptions.map((o) => omit(o, 'shortText'));

const firedTimeLabel = i18n.translate('xpack.infra.metrics.alertFlyout.firedTime', {
defaultMessage: 'time',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export function validateMetricThreshold({
if (!c.aggType) {
errors[id].aggField.push(
i18n.translate('xpack.infra.metrics.alertFlyout.error.aggregationRequired', {
defaultMessage: 'Aggreation is required.',
defaultMessage: 'Aggregation is required.',
})
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,14 +136,14 @@ export const ThresholdExpression = ({
) : null}
<EuiFlexItem grow={false}>
<EuiFormRow
isInvalid={errors[`threshold${i}`].length > 0 || !threshold[i]}
isInvalid={errors[`threshold${i}`]?.length > 0 || !threshold[i]}
error={errors[`threshold${i}`]}
>
<EuiFieldNumber
data-test-subj="alertThresholdInput"
min={0}
value={!threshold || threshold[i] === undefined ? '' : threshold[i]}
isInvalid={errors[`threshold${i}`].length > 0 || !threshold[i]}
isInvalid={errors[`threshold${i}`]?.length > 0 || !threshold[i]}
onChange={(e) => {
const { value } = e.target;
const thresholdVal = value !== '' ? parseFloat(value) : undefined;
Expand Down

0 comments on commit dd4eab4

Please sign in to comment.