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
chore: add unit tests for metric details drawer (#8515)
Amlan Kumar Nandy6afdecbd0f1e
diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsxindex b735e689f2..951ee6b9dd 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsx@@ -104,6 +104,7 @@ function Metadata({if (field.key === 'metric_type') {return (<Select+ data-testid="metric-type-select"options={Object.entries(METRIC_TYPE_VALUES_MAP).map(([key]) => ({value: key,label: METRIC_TYPE_LABEL_MAP[key as MetricType],@@ -121,6 +122,7 @@ function Metadata({if (field.key === 'temporality') {return (<Select+ data-testid="temporality-select"options={Object.values(Temporality).map((key) => ({value: key,label: key,@@ -137,6 +139,7 @@ function Metadata({}return (<Input+ data-testid="description-input"name={field.key}defaultValue={metricMetadata[diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/TopAttributes.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/TopAttributes.tsxdeleted file mode 100644index f5b11fb424..0000000000--- a/frontend/src/container/MetricsExplorer/MetricDetails/TopAttributes.tsx+++ /dev/null@@ -1,67 +0,0 @@-import { Button, Collapse, Typography } from 'antd';-import { useMemo, useState } from 'react';--import { TopAttributesProps } from './types';--function TopAttributes({- items,- title,- loadMore,- hideLoadMore,-}: TopAttributesProps): JSX.Element {- const [activeKey, setActiveKey] = useState<string | string[]>(- 'top-attributes',- );-- const collapseItems = useMemo(- () => [- {- label: (- <div className="metrics-accordion-header">- <Typography.Text>{title}</Typography.Text>- </div>- ),- key: 'top-attributes',- children: (- <div className="top-attributes-content">- {items.map((item) => (- <div className="top-attributes-item" key={item.key}>- <div className="top-attributes-item-progress">- <div className="top-attributes-item-key">{item.key}</div>- <div className="top-attributes-item-count">{item.count}</div>- <div- className="top-attributes-item-progress-bar"- style={{ width: `${item.percentage}%` }}- />- </div>- <div className="top-attributes-item-percentage">- {item.percentage.toFixed(2)}%- </div>- </div>- ))}- {loadMore && !hideLoadMore && (- <div className="top-attributes-load-more">- <Button type="link" onClick={loadMore}>- Load more- </Button>- </div>- )}- </div>- ),- },- ],- [title, items, loadMore, hideLoadMore],- );-- return (- <Collapse- bordered- className="metrics-accordion"- activeKey={activeKey}- onChange={(keys): void => setActiveKey(keys)}- items={collapseItems}- />- );-}--export default TopAttributes;diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsxindex 8f686e4ee4..6b178ad26f 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/AllAttributes.test.tsx@@ -1,6 +1,7 @@import { fireEvent, render, screen } from '@testing-library/react';import { MetricType } from 'api/metricsExplorer/getMetricsList';import * as useHandleExplorerTabChange from 'hooks/useHandleExplorerTabChange';+import * as reactUseHooks from 'react-use';import { MetricDetailsAttribute } from '../../../../api/metricsExplorer/getMetricDetails';import ROUTES from '../../../../constants/routes';@@ -34,6 +35,11 @@ const mockAttributes: MetricDetailsAttribute[] = [},];+const mockUseCopyToClipboard = jest.fn();+jest+ .spyOn(reactUseHooks, 'useCopyToClipboard')+ .mockReturnValue([{ value: 'value1' }, mockUseCopyToClipboard] as any);+describe('AllAttributes', () => {it('renders attributes section with title', () => {render(@@ -165,4 +171,42 @@ describe('AllAttributesValue', () => {);expect(screen.queryByText('Show More')).not.toBeInTheDocument();});++ it('copy button should copy the attribute value to the clipboard', () => {+ render(+ <AllAttributesValue+ filterKey="attribute1"+ filterValue={['value1', 'value2']}+ goToMetricsExploreWithAppliedAttribute={+ mockGoToMetricsExploreWithAppliedAttribute+ }+ />,+ );+ expect(screen.getByText('value1')).toBeInTheDocument();+ fireEvent.click(screen.getByText('value1'));+ expect(screen.getByText('Copy Attribute')).toBeInTheDocument();+ fireEvent.click(screen.getByText('Copy Attribute'));+ expect(mockUseCopyToClipboard).toHaveBeenCalledWith('value1');+ });++ it('explorer button should go to metrics explore with the attribute filter applied', () => {+ render(+ <AllAttributesValue+ filterKey="attribute1"+ filterValue={['value1', 'value2']}+ goToMetricsExploreWithAppliedAttribute={+ mockGoToMetricsExploreWithAppliedAttribute+ }+ />,+ );+ expect(screen.getByText('value1')).toBeInTheDocument();+ fireEvent.click(screen.getByText('value1'));++ expect(screen.getByText('Open in Explorer')).toBeInTheDocument();+ fireEvent.click(screen.getByText('Open in Explorer'));+ expect(mockGoToMetricsExploreWithAppliedAttribute).toHaveBeenCalledWith(+ 'attribute1',+ 'value1',+ );+ });});diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/DashboardsAndAlertsPopover.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/DashboardsAndAlertsPopover.test.tsxnew file mode 100644index 0000000000..1f924519d6--- /dev/null+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/DashboardsAndAlertsPopover.test.tsx@@ -0,0 +1,162 @@+import { fireEvent, render, screen } from '@testing-library/react';+import { QueryParams } from 'constants/query';+import * as useSafeNavigate from 'hooks/useSafeNavigate';++import DashboardsAndAlertsPopover from '../DashboardsAndAlertsPopover';++const mockAlert1 = {+ alert_id: '1',+ alert_name: 'Alert 1',+};+const mockAlert2 = {+ alert_id: '2',+ alert_name: 'Alert 2',+};+const mockDashboard1 = {+ dashboard_id: '1',+ dashboard_name: 'Dashboard 1',+};+const mockDashboard2 = {+ dashboard_id: '2',+ dashboard_name: 'Dashboard 2',+};+const mockAlerts = [mockAlert1, mockAlert2];+const mockDashboards = [mockDashboard1, mockDashboard2];++const mockSafeNavigate = jest.fn();+jest.spyOn(useSafeNavigate, 'useSafeNavigate').mockReturnValue({+ safeNavigate: mockSafeNavigate,+});++const mockSetQuery = jest.fn();+const mockUrlQuery = {+ set: mockSetQuery,+ toString: jest.fn(),+};+jest.mock('hooks/useUrlQuery', () => ({+ __esModule: true,+ default: jest.fn(() => mockUrlQuery),+}));++describe('DashboardsAndAlertsPopover', () => {+ it('renders the popover correctly with multiple dashboards and alerts', () => {+ render(+ <DashboardsAndAlertsPopover+ alerts={mockAlerts}+ dashboards={mockDashboards}+ />,+ );++ expect(+ screen.getByText(`${mockDashboards.length} dashboards`),+ ).toBeInTheDocument();+ expect(+ screen.getByText(`${mockAlerts.length} alert rules`),+ ).toBeInTheDocument();+ });++ it('renders null with no dashboards and alerts', () => {+ const { container } = render(+ <DashboardsAndAlertsPopover alerts={[]} dashboards={[]} />,+ );+ expect(container).toBeEmptyDOMElement();+ });++ it('renders popover with single dashboard and alert', () => {+ render(+ <DashboardsAndAlertsPopover+ alerts={[mockAlert1]}+ dashboards={[mockDashboard1]}+ />,+ );+ expect(screen.getByText(`1 dashboard`)).toBeInTheDocument();+ expect(screen.getByText(`1 alert rule`)).toBeInTheDocument();+ });++ it('renders popover with dashboard id if name is not available', () => {+ render(+ <DashboardsAndAlertsPopover+ alerts={mockAlerts}+ dashboards={[{ ...mockDashboard1, dashboard_name: undefined } as any]}+ />,+ );++ fireEvent.click(screen.getByText(`1 dashboard`));+ expect(screen.getByText(mockDashboard1.dashboard_id)).toBeInTheDocument();+ });++ it('renders popover with alert id if name is not available', () => {+ render(+ <DashboardsAndAlertsPopover+ alerts={[{ ...mockAlert1, alert_name: undefined } as any]}+ dashboards={mockDashboards}+ />,+ );++ fireEvent.click(screen.getByText(`1 alert rule`));+ expect(screen.getByText(mockAlert1.alert_id)).toBeInTheDocument();+ });++ it('navigates to the dashboard when the dashboard is clicked', () => {+ render(+ <DashboardsAndAlertsPopover+ alerts={mockAlerts}+ dashboards={mockDashboards}+ />,+ );++ // Click on 2 dashboards button+ fireEvent.click(screen.getByText(`${mockDashboards.length} dashboards`));+ // Popover showing list of 2 dashboards should be visible+ expect(screen.getByText(mockDashboard1.dashboard_name)).toBeInTheDocument();+ expect(screen.getByText(mockDashboard2.dashboard_name)).toBeInTheDocument();++ // Click on the first dashboard+ fireEvent.click(screen.getByText(mockDashboard1.dashboard_name));++ // Should navigate to the dashboard+ expect(mockSafeNavigate).toHaveBeenCalledWith(+ `/dashboard/${mockDashboard1.dashboard_id}`,+ );+ });++ it('navigates to the alert when the alert is clicked', () => {+ render(+ <DashboardsAndAlertsPopover+ alerts={mockAlerts}+ dashboards={mockDashboards}+ />,+ );++ // Click on 2 alert rules button+ fireEvent.click(screen.getByText(`${mockAlerts.length} alert rules`));+ // Popover showing list of 2 alert rules should be visible+ expect(screen.getByText(mockAlert1.alert_name)).toBeInTheDocument();+ expect(screen.getByText(mockAlert2.alert_name)).toBeInTheDocument();++ // Click on the first alert rule+ fireEvent.click(screen.getByText(mockAlert1.alert_name));++ // Should navigate to the alert rule+ expect(mockSetQuery).toHaveBeenCalledWith(+ QueryParams.ruleId,+ mockAlert1.alert_id,+ );+ });++ it('renders unique dashboards even when there are duplicates', () => {+ render(+ <DashboardsAndAlertsPopover+ alerts={mockAlerts}+ dashboards={[...mockDashboards, mockDashboard1]}+ />,+ );+ expect(+ screen.getByText(`${mockDashboards.length} dashboards`),+ ).toBeInTheDocument();++ fireEvent.click(screen.getByText(`${mockDashboards.length} dashboards`));+ expect(screen.getByText(mockDashboard1.dashboard_name)).toBeInTheDocument();+ expect(screen.getByText(mockDashboard2.dashboard_name)).toBeInTheDocument();+ });+});diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/Metadata.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/Metadata.test.tsxnew file mode 100644index 0000000000..7608b28098--- /dev/null+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/Metadata.test.tsx@@ -0,0 +1,222 @@+/* eslint-disable sonarjs/no-duplicate-string */+import { fireEvent, render, screen } from '@testing-library/react';+import { Temporality } from 'api/metricsExplorer/getMetricDetails';+import { MetricType } from 'api/metricsExplorer/getMetricsList';+import * as useUpdateMetricMetadataHooks from 'hooks/metricsExplorer/useUpdateMetricMetadata';+import * as useNotificationsHooks from 'hooks/useNotifications';++import Metadata from '../Metadata';++const mockUseUpdateMetricMetadata = jest.fn();+jest+ .spyOn(useUpdateMetricMetadataHooks, 'useUpdateMetricMetadata')+ .mockReturnValue({+ mutate: mockUseUpdateMetricMetadata,+ isLoading: false,+ } as any);++const mockErrorNotification = jest.fn();+const mockSuccessNotification = jest.fn();+jest.spyOn(useNotificationsHooks, 'useNotifications').mockReturnValue({+ notifications: {+ error: mockErrorNotification,+ success: mockSuccessNotification,+ },+} as any);++const mockMetricName = 'test_metric';+const mockMetricMetadata = {+ metric_type: MetricType.GAUGE,+ description: 'test_description',+ unit: 'test_unit',+ temporality: Temporality.DELTA,+};+const mockRefetchMetricDetails = jest.fn();++describe('Metadata', () => {+ it('should render the metadata properly', () => {+ render(+ <Metadata+ metricName={mockMetricName}+ metadata={mockMetricMetadata}+ refetchMetricDetails={mockRefetchMetricDetails}+ />,+ );++ expect(screen.getByText('Metric Type')).toBeInTheDocument();+ expect(screen.getByText(mockMetricMetadata.metric_type)).toBeInTheDocument();+ expect(screen.getByText('Description')).toBeInTheDocument();+ expect(screen.getByText(mockMetricMetadata.description)).toBeInTheDocument();+ expect(screen.getByText('Unit')).toBeInTheDocument();+ expect(screen.getByText(mockMetricMetadata.unit)).toBeInTheDocument();+ expect(screen.getByText('Temporality')).toBeInTheDocument();+ expect(screen.getByText(mockMetricMetadata.temporality)).toBeInTheDocument();+ });++ it('editing the metadata should show the form inputs', () => {+ render(+ <Metadata+ metricName={mockMetricName}+ metadata={mockMetricMetadata}+ refetchMetricDetails={mockRefetchMetricDetails}+ />,+ );++ const editButton = screen.getByText('Edit');+ expect(editButton).toBeInTheDocument();+ fireEvent.click(editButton);++ expect(screen.getByTestId('metric-type-select')).toBeInTheDocument();+ expect(screen.getByTestId('temporality-select')).toBeInTheDocument();+ expect(screen.getByTestId('description-input')).toBeInTheDocument();+ });++ it('should update the metadata when the form is submitted', async () => {+ render(+ <Metadata+ metricName={mockMetricName}+ metadata={mockMetricMetadata}+ refetchMetricDetails={mockRefetchMetricDetails}+ />,+ );++ const editButton = screen.getByText('Edit');+ expect(editButton).toBeInTheDocument();+ fireEvent.click(editButton);++ const metricDescriptionInput = screen.getByTestId('description-input');+ expect(metricDescriptionInput).toBeInTheDocument();+ fireEvent.change(metricDescriptionInput, {+ target: { value: 'Updated description' },+ });++ const saveButton = screen.getByText('Save');+ expect(saveButton).toBeInTheDocument();+ fireEvent.click(saveButton);++ expect(mockUseUpdateMetricMetadata).toHaveBeenCalledWith(+ expect.objectContaining({+ metricName: mockMetricName,+ payload: expect.objectContaining({+ description: 'Updated description',+ }),+ }),+ expect.objectContaining({+ onSuccess: expect.any(Function),+ onError: expect.any(Function),+ }),+ );+ });++ it('should show success notification when metadata is updated successfully', async () => {+ render(+ <Metadata+ metricName={mockMetricName}+ metadata={mockMetricMetadata}+ refetchMetricDetails={mockRefetchMetricDetails}+ />,+ );++ const editButton = screen.getByText('Edit');+ fireEvent.click(editButton);++ const metricDescriptionInput = screen.getByTestId('description-input');+ fireEvent.change(metricDescriptionInput, {+ target: { value: 'Updated description' },+ });++ const saveButton = screen.getByText('Save');+ fireEvent.click(saveButton);++ const onSuccessCallback =+ mockUseUpdateMetricMetadata.mock.calls[0][1].onSuccess;+ onSuccessCallback({ statusCode: 200 });++ expect(mockSuccessNotification).toHaveBeenCalledWith({+ message: 'Metadata updated successfully',+ });+ expect(mockRefetchMetricDetails).toHaveBeenCalled();+ });++ it('should show error notification when metadata update fails with non-200 response', async () => {+ render(+ <Metadata+ metricName={mockMetricName}+ metadata={mockMetricMetadata}+ refetchMetricDetails={mockRefetchMetricDetails}+ />,+ );++ const editButton = screen.getByText('Edit');+ fireEvent.click(editButton);++ const metricDescriptionInput = screen.getByTestId('description-input');+ fireEvent.change(metricDescriptionInput, {+ target: { value: 'Updated description' },+ });++ const saveButton = screen.getByText('Save');+ fireEvent.click(saveButton);++ const onSuccessCallback =+ mockUseUpdateMetricMetadata.mock.calls[0][1].onSuccess;+ onSuccessCallback({ statusCode: 500 });++ expect(mockErrorNotification).toHaveBeenCalledWith({+ message:+ 'Failed to update metadata, please try again. If the issue persists, please contact support.',+ });+ });++ it('should show error notification when metadata update fails', async () => {+ render(+ <Metadata+ metricName={mockMetricName}+ metadata={mockMetricMetadata}+ refetchMetricDetails={mockRefetchMetricDetails}+ />,+ );++ const editButton = screen.getByText('Edit');+ fireEvent.click(editButton);++ const metricDescriptionInput = screen.getByTestId('description-input');+ fireEvent.change(metricDescriptionInput, {+ target: { value: 'Updated description' },+ });++ const saveButton = screen.getByText('Save');+ fireEvent.click(saveButton);++ const onErrorCallback = mockUseUpdateMetricMetadata.mock.calls[0][1].onError;++ const error = new Error('Failed to update metadata');+ onErrorCallback(error);++ expect(mockErrorNotification).toHaveBeenCalledWith({+ message:+ 'Failed to update metadata, please try again. If the issue persists, please contact support.',+ });+ });++ it('cancel button should cancel the edit mode', () => {+ render(+ <Metadata+ metricName={mockMetricName}+ metadata={mockMetricMetadata}+ refetchMetricDetails={mockRefetchMetricDetails}+ />,+ );++ const editButton = screen.getByText('Edit');+ expect(editButton).toBeInTheDocument();+ fireEvent.click(editButton);++ const cancelButton = screen.getByText('Cancel');+ expect(cancelButton).toBeInTheDocument();+ fireEvent.click(cancelButton);++ const editButton2 = screen.getByText('Edit');+ expect(editButton2).toBeInTheDocument();+ });+});diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsxindex 0fd0fdf29e..faa76e97db 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/MetricDetails.test.tsx@@ -1,16 +1,16 @@import { fireEvent, render, screen } from '@testing-library/react';-import { MetricDetails } from 'api/metricsExplorer/getMetricDetails';+import { MetricDetails as MetricDetailsType } from 'api/metricsExplorer/getMetricDetails';import { MetricType } from 'api/metricsExplorer/getMetricsList';import ROUTES from 'constants/routes';import * as useGetMetricDetails from 'hooks/metricsExplorer/useGetMetricDetails';import * as useUpdateMetricMetadata from 'hooks/metricsExplorer/useUpdateMetricMetadata';import * as useHandleExplorerTabChange from 'hooks/useHandleExplorerTabChange';-import MetricDetailsView from '../MetricDetails';+import MetricDetails from '../MetricDetails';const mockMetricName = 'test-metric';const mockMetricDescription = 'description for a test metric';-const mockMetricData: MetricDetails = {+const mockMetricData: MetricDetailsType = {name: mockMetricName,description: mockMetricDescription,unit: 'count',@@ -84,7 +84,7 @@ jest.mock('hooks/useSafeNavigate', () => ({describe('MetricDetails', () => {it('renders metric details correctly', () => {render(- <MetricDetailsView+ <MetricDetailsonClose={mockOnClose}isOpenisModalTimeSelection@@ -114,7 +114,7 @@ describe('MetricDetails', () => {},} as any);render(- <MetricDetailsView+ <MetricDetailsonClose={mockOnClose}isOpenmetricName={mockMetricName}@@ -143,7 +143,7 @@ describe('MetricDetails', () => {} as any);render(- <MetricDetailsView+ <MetricDetailsonClose={mockOnClose}isOpenmetricName={mockMetricName}@@ -162,7 +162,7 @@ describe('MetricDetails', () => {} as any);render(- <MetricDetailsView+ <MetricDetailsonClose={mockOnClose}isOpenmetricName={mockMetricName}@@ -179,7 +179,7 @@ describe('MetricDetails', () => {.spyOn(useGetMetricDetails, 'useGetMetricDetails').mockReturnValue(mockUseGetMetricDetailsData as any);render(- <MetricDetailsView+ <MetricDetailsonClose={mockOnClose}isOpenmetricName={mockMetricName}@@ -204,7 +204,7 @@ describe('MetricDetails', () => {},} as any);render(- <MetricDetailsView+ <MetricDetailsonClose={mockOnClose}isOpenmetricName={mockMetricName}diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/utils.test.ts b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/utils.test.tsnew file mode 100644index 0000000000..eed2756b21--- /dev/null+++ b/frontend/src/container/MetricsExplorer/MetricDetails/__tests__/utils.test.ts@@ -0,0 +1,259 @@+import { Temporality } from 'api/metricsExplorer/getMetricDetails';+import { MetricType } from 'api/metricsExplorer/getMetricsList';++import {+ determineIsMonotonic,+ formatTimestampToReadableDate,+ getMetricDetailsQuery,+} from '../utils';++describe('MetricDetails utils', () => {+ describe('determineIsMonotonic', () => {+ it('should return true for histogram metrics', () => {+ expect(determineIsMonotonic(MetricType.HISTOGRAM)).toBe(true);+ });++ it('should return true for exponential histogram metrics', () => {+ expect(determineIsMonotonic(MetricType.EXPONENTIAL_HISTOGRAM)).toBe(true);+ });++ it('should return false for gauge metrics', () => {+ expect(determineIsMonotonic(MetricType.GAUGE)).toBe(false);+ });++ it('should return false for summary metrics', () => {+ expect(determineIsMonotonic(MetricType.SUMMARY)).toBe(false);+ });++ it('should return true for sum metrics with cumulative temporality', () => {+ expect(determineIsMonotonic(MetricType.SUM, Temporality.CUMULATIVE)).toBe(+ true,+ );+ });++ it('should return false for sum metrics with delta temporality', () => {+ expect(determineIsMonotonic(MetricType.SUM, Temporality.DELTA)).toBe(false);+ });++ it('should return false by default', () => {+ expect(determineIsMonotonic('' as MetricType, '' as Temporality)).toBe(+ false,+ );+ });+ });++ describe('formatTimestampToReadableDate', () => {+ const FEW_SECONDS_AGO = 'Few seconds ago';++ beforeEach(() => {+ jest.useFakeTimers();+ jest.setSystemTime(new Date('2024-01-15T12:00:00.000Z'));+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ it('should return "Few seconds ago" for timestamps less than 60 seconds ago', () => {+ const timestamp = '2024-01-15T11:59:30.000Z';+ expect(formatTimestampToReadableDate(timestamp)).toBe(FEW_SECONDS_AGO);+ });++ it('should return "1 minute ago" for exactly 1 minute ago', () => {+ const timestamp = '2024-01-15T11:59:00.000Z';+ expect(formatTimestampToReadableDate(timestamp)).toBe('1 minute ago');+ });++ it('should return "X minutes ago" for multiple minutes ago', () => {+ const timestamp = '2024-01-15T11:55:00.000Z';+ expect(formatTimestampToReadableDate(timestamp)).toBe('5 minutes ago');+ });++ it('should return "1 hour ago" for exactly 1 hour ago', () => {+ const timestamp = '2024-01-15T11:00:00.000Z';+ expect(formatTimestampToReadableDate(timestamp)).toBe('1 hour ago');+ });++ it('should return "X hours ago" for multiple hours ago', () => {+ const timestamp = '2024-01-15T09:00:00.000Z';+ expect(formatTimestampToReadableDate(timestamp)).toBe('3 hours ago');+ });++ it('should return "Yesterday at HH:MM" for exactly 1 day ago', () => {+ const timestamp = '2024-01-14T12:00:00.000Z';+ const expectedTime = new Date(timestamp).toLocaleTimeString('en-US', {+ hour: '2-digit',+ minute: '2-digit',+ hour12: false,+ });+ expect(formatTimestampToReadableDate(timestamp)).toBe(+ `Yesterday at ${expectedTime}`,+ );+ });++ it('should return "X days ago" for multiple days ago (less than 7 days)', () => {+ const timestamp = '2024-01-12T12:00:00.000Z';+ expect(formatTimestampToReadableDate(timestamp)).toBe('3 days ago');+ });++ it('should return localized date string for dates 7 or more days ago', () => {+ const oldTimestamp = '2024-01-01T12:00:00.000Z';+ const result = formatTimestampToReadableDate(oldTimestamp);+ expect(result).not.toBe(FEW_SECONDS_AGO);+ expect(typeof result).toBe('string');+ });++ it('should handle future timestamps correctly', () => {+ const timestamp = '2024-01-16T12:00:00.000Z';+ const result = formatTimestampToReadableDate(timestamp);+ expect(result).toBe(FEW_SECONDS_AGO);+ });+ });++ describe('getMetricDetailsQuery', () => {+ const TEST_METRIC_NAME = 'test_metric';+ const API_GATEWAY = 'api-gateway';++ it('should create correct query for SUM metric type', () => {+ const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.SUM);++ expect(query.builder.queryData[0]?.aggregateAttribute.key).toBe(+ TEST_METRIC_NAME,+ );+ expect(query.builder.queryData[0]?.aggregateAttribute.type).toBe(+ MetricType.SUM,+ );+ expect(query.builder.queryData[0]?.aggregateOperator).toBe('rate');+ expect(query.builder.queryData[0]?.timeAggregation).toBe('rate');+ expect(query.builder.queryData[0]?.spaceAggregation).toBe('sum');+ });++ it('should create correct query for GAUGE metric type', () => {+ const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.GAUGE);++ expect(query.builder.queryData[0]?.aggregateAttribute.key).toBe(+ TEST_METRIC_NAME,+ );+ expect(query.builder.queryData[0]?.aggregateAttribute.type).toBe(+ MetricType.GAUGE,+ );+ expect(query.builder.queryData[0]?.aggregateOperator).toBe('avg');+ expect(query.builder.queryData[0]?.timeAggregation).toBe('avg');+ expect(query.builder.queryData[0]?.spaceAggregation).toBe('avg');+ });++ it('should create correct query for SUMMARY metric type', () => {+ const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.SUMMARY);++ expect(query.builder.queryData[0]?.aggregateAttribute.key).toBe(+ TEST_METRIC_NAME,+ );+ expect(query.builder.queryData[0]?.aggregateAttribute.type).toBe(+ MetricType.SUMMARY,+ );+ expect(query.builder.queryData[0]?.aggregateOperator).toBe('noop');+ expect(query.builder.queryData[0]?.timeAggregation).toBe('noop');+ expect(query.builder.queryData[0]?.spaceAggregation).toBe('sum');+ });++ it('should create correct query for HISTOGRAM metric type', () => {+ const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.HISTOGRAM);++ expect(query.builder.queryData[0]?.aggregateAttribute.key).toBe(+ TEST_METRIC_NAME,+ );+ expect(query.builder.queryData[0]?.aggregateAttribute.type).toBe(+ MetricType.HISTOGRAM,+ );+ expect(query.builder.queryData[0]?.aggregateOperator).toBe('noop');+ expect(query.builder.queryData[0]?.timeAggregation).toBe('noop');+ expect(query.builder.queryData[0]?.spaceAggregation).toBe('p90');+ });++ it('should create correct query for EXPONENTIAL_HISTOGRAM metric type', () => {+ const query = getMetricDetailsQuery(+ TEST_METRIC_NAME,+ MetricType.EXPONENTIAL_HISTOGRAM,+ );++ expect(query.builder.queryData[0]?.aggregateAttribute.key).toBe(+ TEST_METRIC_NAME,+ );+ expect(query.builder.queryData[0]?.aggregateAttribute.type).toBe(+ MetricType.EXPONENTIAL_HISTOGRAM,+ );+ expect(query.builder.queryData[0]?.aggregateOperator).toBe('noop');+ expect(query.builder.queryData[0]?.timeAggregation).toBe('noop');+ expect(query.builder.queryData[0]?.spaceAggregation).toBe('p90');+ });++ it('should create query with default values for unknown metric type', () => {+ const query = getMetricDetailsQuery(TEST_METRIC_NAME, undefined);++ expect(query.builder.queryData[0]?.aggregateAttribute.key).toBe(+ TEST_METRIC_NAME,+ );+ expect(query.builder.queryData[0]?.aggregateAttribute.type).toBe('');+ expect(query.builder.queryData[0]?.aggregateOperator).toBe('noop');+ expect(query.builder.queryData[0]?.timeAggregation).toBe('noop');+ expect(query.builder.queryData[0]?.spaceAggregation).toBe('noop');+ });++ it('should include filter when provided', () => {+ const filter = { key: 'service', value: API_GATEWAY };+ const query = getMetricDetailsQuery(+ TEST_METRIC_NAME,+ MetricType.SUM,+ filter,+ );++ expect(query.builder.queryData[0]?.filters.items).toHaveLength(1);+ expect(query.builder.queryData[0]?.filters.items[0]?.key?.key).toBe(+ 'service',+ );+ expect(query.builder.queryData[0]?.filters.items[0]?.value).toBe(+ API_GATEWAY,+ );+ expect(query.builder.queryData[0]?.filters.items[0]?.op).toBe('=');+ });++ it('should include groupBy when provided', () => {+ const groupBy = 'service';+ const query = getMetricDetailsQuery(+ TEST_METRIC_NAME,+ MetricType.SUM,+ undefined,+ groupBy,+ );++ expect(query.builder.queryData[0]?.groupBy).toHaveLength(1);+ expect(query.builder.queryData[0]?.groupBy[0]?.key).toBe('service');+ expect(query.builder.queryData[0]?.groupBy[0]?.type).toBe('tag');+ });++ it('should include both filter and groupBy when provided', () => {+ const filter = { key: 'service', value: API_GATEWAY };+ const groupBy = 'endpoint';+ const query = getMetricDetailsQuery(+ TEST_METRIC_NAME,+ MetricType.SUM,+ filter,+ groupBy,+ );++ expect(query.builder.queryData[0]?.filters.items).toHaveLength(1);+ expect(query.builder.queryData[0]?.groupBy).toHaveLength(1);+ expect(query.builder.queryData[0]?.filters.items[0]?.key?.key).toBe(+ 'service',+ );+ expect(query.builder.queryData[0]?.groupBy[0]?.key).toBe('endpoint');+ });++ it('should not include filters or groupBy when not provided', () => {+ const query = getMetricDetailsQuery(TEST_METRIC_NAME, MetricType.SUM);++ expect(query.builder.queryData[0]?.filters.items).toHaveLength(0);+ expect(query.builder.queryData[0]?.groupBy).toHaveLength(0);+ });+ });+});diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/types.ts b/frontend/src/container/MetricsExplorer/MetricDetails/types.tsindex 2453adf328..b74b55499b 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/types.ts+++ b/frontend/src/container/MetricsExplorer/MetricDetails/types.ts@@ -36,14 +36,3 @@ export interface AllAttributesValueProps {filterValue: string[];goToMetricsExploreWithAppliedAttribute: (key: string, value: string) => void;}--export interface TopAttributesProps {- items: Array<{- key: string;- count: number;- percentage: number;- }>;- title: string;- loadMore?: () => void;- hideLoadMore?: boolean;-}diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/utils.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/utils.tsxindex c12130e284..a57d27a6f8 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/utils.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/utils.tsx@@ -108,6 +108,7 @@ export function getMetricDetailsQuery(id: `${metricName}----${metricType}---string--`,isColumn: true,isJSON: false,+ dataType: DataTypes.String,},aggregateOperator,timeAggregation,