Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

10.2 KB
Raw Blame
import '@testing-library/jest-dom'

import { cleanup, render, screen } from '@testing-library/react'

import { createDefaultTooltipAccessor, ensureJsdom, getChart, hoverUntilTooltip } from '@posthog/quill-charts/testing'

import type { MetricsDisplaySettings } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'

import type { MetricsExemplar } from '../components/MetricsExemplarMarkers'
import type { MetricsChartSeries } from '../components/metricsSeries'
import { MetricsPanel } from './MetricsPanel'

const BUCKETS = ['2026-08-01T10:00:00Z', '2026-08-01T11:00:00Z', '2026-08-01T12:00:00Z']

function seriesWith(
    labels: Record<string, string>,
    values: (number | null)[],
    metricName?: string,
    unit?: string
): MetricsChartSeries {
    return { labels, points: BUCKETS.map((time, i) => ({ time, value: values[i] })), metricName, unit }
}

function renderPanel(
    series: MetricsChartSeries[],
    display?: MetricsDisplaySettings,
    exemplars?: MetricsExemplar[]
): void {
    render(<MetricsPanel series={series} fallbackName="http.requests" display={display} exemplars={exemplars} />)
}

describe('MetricsPanel', () => {
    describe('time-series (line/area/bar)', () => {
        beforeEach(() => {
            ensureJsdom()
            initKeaTests()
        })

        afterEach(() => cleanup())

        it('draws one line per series by default', () => {
            renderPanel([seriesWith({ service: 'checkout' }, [1, 2, 3]), seriesWith({ service: 'billing' }, [4, 5, 6])])
            expect(getChart().seriesCount).toBe(2)
        })

        it.each([
            ['renders no display as a line chart', undefined, 'line'],
            ['renders the area display as a line chart', 'area' as const, 'line'],
            ['renders the bar display as a bar chart', 'bar' as const, 'bar'],
        ])('%s', (_name, type, expectedChart) => {
            renderPanel([seriesWith({ service: 'a' }, [1, 2, 3]), seriesWith({ service: 'b' }, [4, 5, 6])], { type })
            expect(getChart().seriesCount).toBe(2)
            expect(screen.getByTestId(`hog-chart-timeseries-${expectedChart}-legend`)).toBeInTheDocument()
        })

        it('falls back to a line chart for an unknown display type', () => {
            renderPanel([seriesWith({ service: 'a' }, [1, 2, 3])], { type: 'pie' as never })
            expect(getChart().seriesCount).toBe(1)
        })

        it('renders a clickable dot per traced exemplar', () => {
            renderPanel([seriesWith({}, [1, 2, 3])], undefined, [
                { timeMs: Date.parse(BUCKETS[1]), onClick: jest.fn(), tooltipLabel: 'test exemplar' },
            ])
            expect(screen.getAllByTestId('metrics-exemplar-marker')).toHaveLength(1)
        })

        // A null bucket is a non-representable aggregate. quill draws only numbers, so it renders as 0
        // until the quill null-data change; dropping it would shift later values a bucket left.
        it('charts a null bucket as zero rather than dropping the point', async () => {
            renderPanel([seriesWith({}, [1, null, 3])])
            const chart = getChart()
            const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 1, BUCKETS.length))
            expect(tooltip.value('http.requests')).toBe('0')
        })

        it('formats the y axis and tooltip with the resolved unit', async () => {
            renderPanel([seriesWith({}, [250, 1500, 3000], 'http.duration', 'ms')])
            const chart = getChart()
            expect(chart.yTicks().some((tick) => tick.endsWith(' s'))).toBe(true)
            const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 0, BUCKETS.length))
            expect(tooltip.value('http.duration')).toBe('250 ms')
        })

        it('labels every ratio tick on one scale when the data exceeds 1', () => {
            renderPanel([seriesWith({}, [0, 1, 2], 'load', '1')])
            const ticks = getChart().yTicks()
            expect(ticks.length).toBeGreaterThan(1)
            expect(ticks.some((tick) => tick.endsWith('%'))).toBe(false)
        })

        it('draws a goal line above the data', () => {
            renderPanel([seriesWith({}, [1, 2, 3])], { goalLines: [{ label: 'SLO', value: 10 }] })
            expect(screen.getByText('SLO')).toBeInTheDocument()
        })
    })

    describe('scalar and categorical panels', () => {
        beforeEach(() => {
            ensureJsdom()
            initKeaTests()
        })

        afterEach(() => cleanup())

        it('renders a single stat with the resolved unit, and no metric name or time at rest', () => {
            renderPanel([seriesWith({}, [100, 200, 340], 'http.duration', 'ms')], { type: 'stat' })
            expect(screen.getByText('340 ms')).toBeInTheDocument()
            expect(screen.queryByText('http.duration')).not.toBeInTheDocument()
            expect(screen.queryByText(/12:00/)).not.toBeInTheDocument()
        })

        it('stat uses the reduce reducer', () => {
            renderPanel([seriesWith({}, [100, 200, 340], 'm', 'ms')], { type: 'stat', reduce: 'max' })
            expect(screen.getByText('340 ms')).toBeInTheDocument()
        })

        it('stat maps the deprecated statSummary', () => {
            renderPanel([seriesWith({}, [100, 200, 300], 'm', 'ms')], { type: 'stat', statSummary: 'average' })
            expect(screen.getByText('200 ms')).toBeInTheDocument()
        })

        it('renders one stat card per grouped series', () => {
            renderPanel([seriesWith({ service: 'a' }, [1, 2, 3]), seriesWith({ service: 'b' }, [4, 5, 6])], {
                type: 'stat',
            })
            expect(screen.getByText('service=a')).toBeInTheDocument()
            expect(screen.getByText('service=b')).toBeInTheDocument()
        })

        it('renders the table panel with label and reducer columns', () => {
            renderPanel([seriesWith({ service: 'api', pod: 'p1' }, [10, 20, 30])], { type: 'table', reduce: 'last' })
            expect(screen.getByText('service')).toBeInTheDocument()
            expect(screen.getByText('pod')).toBeInTheDocument()
            expect(screen.getByText('api')).toBeInTheDocument()
            expect(screen.getByText('30')).toBeInTheDocument()
        })

        it('formats every ratio cell of the table on one scale', () => {
            renderPanel([seriesWith({}, [0.5, 1, 2], 'load', '1')], { type: 'table', legendCalcs: ['min', 'max'] })
            expect(screen.getByText('0.5')).toBeInTheDocument()
            expect(screen.getByText('2')).toBeInTheDocument()
            expect(screen.queryByText('50%')).not.toBeInTheDocument()
        })

        it('formats a ratio gauge value and its bounds on one scale', () => {
            renderPanel([seriesWith({}, [0, 0, 0.5], 'load', '1')], { type: 'gauge', yAxis: { min: 0, max: 2 } })
            expect(screen.getByText('0.5')).toBeInTheDocument()
            expect(screen.getByText('0 – 2')).toBeInTheDocument()
        })

        it('renders the gauge arc with a formatted value and bounds', () => {
            renderPanel([seriesWith({}, [0, 0, 40], 'cpu', '%')], {
                type: 'gauge',
                yAxis: { min: 0, max: 100 },
            })
            expect(screen.getByText('40%')).toBeInTheDocument()
            expect(screen.getByText('0% – 100%')).toBeInTheDocument()
        })

        it('renders the bar gauge with one bar per grouped series', () => {
            renderPanel([seriesWith({ pod: 'a' }, [1, 2, 10]), seriesWith({ pod: 'b' }, [1, 2, 20])], {
                type: 'bargauge',
            })
            expect(getChart().seriesCount).toBe(1)
            expect(screen.getByText('pod=a')).toBeInTheDocument()
            expect(screen.getByText('pod=b')).toBeInTheDocument()
        })

        it('shows No data for an empty result on a scalar panel', () => {
            renderPanel([seriesWith({}, [])], { type: 'stat' })
            expect(screen.getByText('No data')).toBeInTheDocument()
        })

        it('drops the unit everywhere on a mixed-unit result rather than mislabeling one series', () => {
            renderPanel(
                [
                    seriesWith({ service: 'a' }, [100, 200, 340], 'duration', 'ms'),
                    seriesWith({ service: 'b' }, [0.1, 0.2, 0.34], 'latency', 's'),
                ],
                { type: 'table', reduce: 'last' }
            )
            expect(screen.getByText('340')).toBeInTheDocument()
            expect(screen.getByText('0.34')).toBeInTheDocument()
            expect(screen.queryByText('340 ms')).not.toBeInTheDocument()
            expect(screen.queryByText('0.34 s')).not.toBeInTheDocument()
        })

        it('drops the unit on a mixed-unit stat rather than mislabeling one series', () => {
            renderPanel([seriesWith({}, [1, 2, 3], 'a', 'ms'), seriesWith({}, [4, 5, 6], 'b', 's')], { type: 'stat' })
            expect(screen.getByText('3')).toBeInTheDocument()
            expect(screen.getByText('6')).toBeInTheDocument()
        })

        it('extends the gauge max past the value when thresholds end below it', () => {
            renderPanel([seriesWith({}, [0, 0, 150], 'cpu', '%')], {
                type: 'gauge',
                thresholds: [
                    { value: 50, color: 'green' },
                    { value: 90, color: 'red' },
                ],
            })
            // The max must contain the value, or the arc reads full at 150 of a "50 – 90" range.
            expect(screen.getByText((_content, el) => el?.textContent === '50% – 150%')).toBeInTheDocument()
        })

        it('shows No data on the gauge when every point is null', () => {
            renderPanel([seriesWith({ pod: 'a' }, [null, null, null])], { type: 'gauge' })
            expect(screen.getByText('No data')).toBeInTheDocument()
            expect(screen.queryByRole('img')).not.toBeInTheDocument()
        })

        it('deduplicates and caps the table reducer columns', () => {
            renderPanel([seriesWith({ pod: 'a' }, [1, 2, 3])], {
                type: 'table',
                legendCalcs: ['last', 'last', 'mean', 'min', 'max', 'sum', 'delta', 'mean'],
            })
            expect(screen.getAllByText('last')).toHaveLength(1)
            expect(screen.queryByText('delta')).toBeInTheDocument()
        })
    })
})