Alerting: do not overwrite existing alert rule condition (#49920)

This commit is contained in:
Gilles De Mey 2022-06-01 11:28:21 +02:00 committed by GitHub
parent 4b1c4f7240
commit 82e9f4e7e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 47 additions and 4 deletions

View File

@ -0,0 +1,39 @@
import { render, screen } from '@testing-library/react';
import React, { FC } from 'react';
import { FormProvider, useForm, UseFormProps } from 'react-hook-form';
import { ExpressionDatasourceUID } from 'app/features/expressions/ExpressionDatasource';
import { RuleFormValues } from '../../types/rule-form';
import { ConditionField } from './ConditionField';
const FormProviderWrapper: FC<UseFormProps> = ({ children, ...props }) => {
const methods = useForm({ ...props });
return <FormProvider {...methods}>{children}</FormProvider>;
};
describe('ConditionField', () => {
it('should render the correct condition when editing existing rule', () => {
const existingRule = {
name: 'ConditionsTest',
condition: 'B',
queries: [
{ refId: 'A' },
{ refId: 'B', datasourceUid: ExpressionDatasourceUID },
{ refId: 'C', datasourceUid: ExpressionDatasourceUID },
],
} as RuleFormValues;
const form = (
<FormProviderWrapper defaultValues={existingRule}>
<ConditionField existing={true} />
</FormProviderWrapper>
);
render(form);
expect(screen.getByLabelText(/^A/)).not.toBeChecked();
expect(screen.getByLabelText(/^B/)).toBeChecked();
expect(screen.getByLabelText(/^C/)).not.toBeChecked();
});
});

View File

@ -9,7 +9,11 @@ import { ExpressionDatasourceUID } from 'app/features/expressions/ExpressionData
import { RuleFormValues } from '../../types/rule-form';
export const ConditionField: FC = () => {
interface Props {
existing?: boolean;
}
export const ConditionField: FC<Props> = ({ existing = false }) => {
const {
watch,
setValue,
@ -37,10 +41,10 @@ export const ConditionField: FC = () => {
// automatically use the last expression when new expressions have been added
useEffect(() => {
const lastExpression = last(expressions);
if (lastExpression) {
if (lastExpression && !existing) {
setValue('condition', lastExpression.refId, { shouldValidate: true });
}
}, [expressions, setValue]);
}, [expressions, setValue, existing]);
// reset condition if option no longer exists or if it is unset, but there are options available
useEffect(() => {

View File

@ -22,7 +22,7 @@ export const QueryAndAlertConditionStep: FC<Props> = ({ editingExistingRule }) =
<RuleEditorSection stepNo={1} title="Set a query and alert condition">
<AlertType editingExistingRule={editingExistingRule} />
{type && <Query />}
{isGrafanaManagedType && <ConditionField />}
{isGrafanaManagedType && <ConditionField existing={editingExistingRule} />}
</RuleEditorSection>
);
};