SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
import { navigate } from 'lib/router/navigation';
import { render, screen, userEvent } from 'tests/test-utils';
import { AlertTypes } from 'types/api/alerts/alertTypes';
import { INITIAL_CREATE_ALERT_STATE } from '../constants';
import { CreateAlertProvider, useCreateAlertState } from '../index';
import { AlertThresholdMatchType } from '../types';
// The provider only needs a query with a unit + empty builder for these assertions.
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: (): unknown => ({
currentQuery: {
unit: 'bytes',
builder: { queryData: [], queryFormulas: [] },
},
redirectWithQueryBuilderData: jest.fn(),
}),
}));
const mutation = { mutate: jest.fn(), isLoading: false };
jest.mock('api/generated/services/rules', () => ({
useCreateRule: (): unknown => mutation,
useTestRule: (): unknown => mutation,
useUpdateRuleByID: (): unknown => mutation,
}));
function Probe(): JSX.Element {
const { thresholdState, evaluationWindow } = useCreateAlertState();
return (
<div>
<span data-testid="match-type">{thresholdState.matchType}</span>
<span data-testid="operator">{thresholdState.operator}</span>
<span data-testid="threshold-count">{thresholdState.thresholds.length}</span>
<span data-testid="threshold-value">
{thresholdState.thresholds[0]?.thresholdValue}
</span>
<span data-testid="window-type">{evaluationWindow.windowType}</span>
</div>
);
}
function renderWithSearch(search: string): void {
render(
<CreateAlertProvider initialAlertType={AlertTypes.METRICS_BASED_ALERT}>
<Probe />
</CreateAlertProvider>,
undefined,
{ initialRoute: `/alerts/new${search}` },
);
}
const clickTestId = async (testId: string): Promise<void> => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
await user.click(screen.getByTestId(testId));
};
function serializeThreshold(thresholdValue: number): string {
return encodeURIComponent(
JSON.stringify([
{
id: 't1',
label: 'critical',
thresholdValue,
recoveryThresholdValue: null,
unit: 'bytes',
channels: [],
color: '#F1575F',
},
]),
);
}
describe('CreateAlertProvider — URL-declared prefill (issue #5291)', () => {
it('applies matchType, operator, and thresholds without the meter window', () => {
// Dashboard-style prefill: no evaluationWindowPreset → default window.
renderWithSearch(
`?matchType=on_average&compareOp=below&thresholds=${serializeThreshold(90)}`,
);
expect(screen.getByTestId('match-type')).toHaveTextContent('on_average');
expect(screen.getByTestId('operator')).toHaveTextContent('below');
expect(screen.getByTestId('threshold-count')).toHaveTextContent('1');
expect(screen.getByTestId('threshold-value')).toHaveTextContent('90');
// The meter evaluation-window preset must NOT fire.
expect(screen.getByTestId('window-type')).toHaveTextContent('rolling');
});
it('adjusts only the occurrence type when no thresholds are supplied', () => {
renderWithSearch(`?matchType=in_total`);
expect(screen.getByTestId('match-type')).toHaveTextContent('in_total');
// The default single critical threshold and operator are retained.
expect(screen.getByTestId('threshold-count')).toHaveTextContent('1');
expect(screen.getByTestId('threshold-value')).toHaveTextContent('0');
expect(screen.getByTestId('operator')).toHaveTextContent('above');
expect(screen.getByTestId('window-type')).toHaveTextContent('rolling');
});
it('starts new anomaly alerts at 3 deviations', () => {
renderWithSearch(`?ruleType=anomaly_rule`);
expect(screen.getByTestId('threshold-count')).toHaveTextContent('1');
expect(screen.getByTestId('threshold-value')).toHaveTextContent('3');
});
it('applies the meter evaluation window when the preset is declared', () => {
// Ingestion-style prefill: explicit in_total + meter preset.
renderWithSearch(
`?matchType=in_total&evaluationWindowPreset=meter&thresholds=${serializeThreshold(
500,
)}`,
);
expect(screen.getByTestId('match-type')).toHaveTextContent('in_total');
expect(screen.getByTestId('threshold-value')).toHaveTextContent('500');
expect(screen.getByTestId('window-type')).toHaveTextContent('cumulative');
});
});
// Reproduces the #12137 regression: on the alert overview page the query builder
// rewrites location.search after the alert loads, which used to re-run the prefill
// effect and RESET the loaded threshold back to 0.
function SearchMutator({
to = '/alerts/overview?compositeQuery=normalized&ruleId=r1',
}: {
to?: string;
}): JSX.Element {
return (
<button
type="button"
data-testid="mutate-search"
onClick={(): void => navigate(to, { replace: true })}
>
change search
</button>
);
}
describe('CreateAlertProvider — edit mode ignores URL prefill', () => {
it('keeps loaded thresholds when the query builder rewrites location.search', async () => {
const initialAlertState = {
...INITIAL_CREATE_ALERT_STATE,
threshold: {
...INITIAL_CREATE_ALERT_STATE.threshold,
matchType: AlertThresholdMatchType.AT_LEAST_ONCE,
thresholds: [
{
...INITIAL_CREATE_ALERT_STATE.threshold.thresholds[0],
thresholdValue: 245,
},
],
},
};
render(
<CreateAlertProvider
initialAlertType={AlertTypes.METRICS_BASED_ALERT}
isEditMode
ruleId="r1"
initialAlertState={initialAlertState}
>
<Probe />
<SearchMutator />
</CreateAlertProvider>,
undefined,
{ initialRoute: '/alerts/overview?ruleId=r1' },
);
expect(screen.getByTestId('threshold-value')).toHaveTextContent('245');
// Simulate the query builder normalizing the query into the URL post-load.
await clickTestId('mutate-search');
expect(screen.getByTestId('threshold-value')).toHaveTextContent('245');
});
it('ignores prefill params that are present on an edit URL', () => {
// A deep link into the editor can carry the create form's prefill params.
// The loaded rule has to win, or opening an edited rule from such a link
// would silently rewrite its condition.
const initialAlertState = {
...INITIAL_CREATE_ALERT_STATE,
threshold: {
...INITIAL_CREATE_ALERT_STATE.threshold,
matchType: AlertThresholdMatchType.AT_LEAST_ONCE,
thresholds: [
{
...INITIAL_CREATE_ALERT_STATE.threshold.thresholds[0],
thresholdValue: 245,
},
],
},
};
render(
<CreateAlertProvider
initialAlertType={AlertTypes.METRICS_BASED_ALERT}
isEditMode
ruleId="r1"
initialAlertState={initialAlertState}
>
<Probe />
</CreateAlertProvider>,
undefined,
{
initialRoute: `/alerts/overview?ruleId=r1&matchType=in_total&compareOp=below&thresholds=${serializeThreshold(
90,
)}`,
},
);
expect(screen.getByTestId('threshold-value')).toHaveTextContent('245');
expect(screen.getByTestId('match-type')).toHaveTextContent('at_least_once');
});
});
function ThresholdSetter(): JSX.Element {
const { thresholdState, setThresholdState } = useCreateAlertState();
return (
<button
type="button"
data-testid="set-threshold"
onClick={(): void =>
setThresholdState({
type: 'SET_THRESHOLDS',
payload: [{ ...thresholdState.thresholds[0], thresholdValue: 245 }],
})
}
>
set threshold
</button>
);
}
describe('CreateAlertProvider — create mode', () => {
it('keeps edited thresholds when running the query rewrites location.search', async () => {
render(
<CreateAlertProvider initialAlertType={AlertTypes.METRICS_BASED_ALERT}>
<Probe />
<ThresholdSetter />
<SearchMutator to="/alerts/new?alertType=METRIC_BASED_ALERT&compositeQuery=ran" />
</CreateAlertProvider>,
undefined,
{ initialRoute: '/alerts/new?alertType=METRIC_BASED_ALERT' },
);
await clickTestId('set-threshold');
expect(screen.getByTestId('threshold-value')).toHaveTextContent('245');
await clickTestId('mutate-search');
expect(screen.getByTestId('threshold-value')).toHaveTextContent('245');
});
});
function AnomalySwitcher(): JSX.Element {
const { setAlertType } = useCreateAlertState();
return (
<button
type="button"
data-testid="switch-to-anomaly"
onClick={(): void => setAlertType(AlertTypes.ANOMALY_BASED_ALERT)}
>
switch to anomaly
</button>
);
}
describe('CreateAlertProvider — edit mode type switch', () => {
it('starts the anomaly condition at 3 deviations instead of the loaded threshold', async () => {
const initialAlertState = {
...INITIAL_CREATE_ALERT_STATE,
threshold: {
...INITIAL_CREATE_ALERT_STATE.threshold,
thresholds: [
{
...INITIAL_CREATE_ALERT_STATE.threshold.thresholds[0],
thresholdValue: 500,
},
],
},
};
render(
<CreateAlertProvider
initialAlertType={AlertTypes.METRICS_BASED_ALERT}
isEditMode
ruleId="r1"
initialAlertState={initialAlertState}
>
<Probe />
<AnomalySwitcher />
</CreateAlertProvider>,
undefined,
{ initialRoute: '/alerts/overview?ruleId=r1' },
);
expect(screen.getByTestId('threshold-value')).toHaveTextContent('500');
await clickTestId('switch-to-anomaly');
expect(screen.getByTestId('threshold-value')).toHaveTextContent('3');
});
it('keeps the meter preset from bringing back a cumulative window for anomaly', async () => {
render(
<CreateAlertProvider initialAlertType={AlertTypes.METRICS_BASED_ALERT}>
<Probe />
<AnomalySwitcher />
</CreateAlertProvider>,
undefined,
{
initialRoute: '/alerts/new?matchType=in_total&evaluationWindowPreset=meter',
},
);
expect(screen.getByTestId('window-type')).toHaveTextContent('cumulative');
await clickTestId('switch-to-anomaly');
expect(screen.getByTestId('window-type')).toHaveTextContent('rolling');
});
it('moves a cumulative window back to rolling when switching to anomaly', async () => {
render(
<CreateAlertProvider
initialAlertType={AlertTypes.METRICS_BASED_ALERT}
isEditMode
ruleId="r1"
initialAlertState={{
...INITIAL_CREATE_ALERT_STATE,
evaluationWindow: {
...INITIAL_CREATE_ALERT_STATE.evaluationWindow,
windowType: 'cumulative',
timeframe: 'currentHour',
},
}}
>
<Probe />
<AnomalySwitcher />
</CreateAlertProvider>,
undefined,
{ initialRoute: '/alerts/overview?ruleId=r1' },
);
expect(screen.getByTestId('window-type')).toHaveTextContent('cumulative');
await clickTestId('switch-to-anomaly');
expect(screen.getByTestId('window-type')).toHaveTextContent('rolling');
});
});