From 64183d16a60afb3b5bb68e55e043ce6b069ccaac Mon Sep 17 00:00:00 2001 From: Drew Davis Date: Sat, 21 Nov 2026 09:47:06 -0500 Subject: [PATCH] test(app): replace jest.Mock casts with jest.mocked --- packages/app/package.json | 2 +- .../src/__tests__/SessionSidePanel.test.tsx | 8 +- .../app/src/__tests__/Spotlights.test.tsx | 18 +- .../src/__tests__/dashboard.remote.test.ts | 51 +++- packages/app/src/__tests__/source.test.ts | 31 +- .../ServiceMap/__tests__/utils.test.ts | 20 +- .../__tests__/TimelineMinimap.test.tsx | 14 +- .../__tests__/ActiveFilterPills.test.tsx | 62 ++-- .../components/__tests__/DBBarChart.test.tsx | 215 ++++++++------ .../__tests__/DBDeltaChart.test.tsx | 101 ++++--- .../__tests__/DBHistogramChart.test.tsx | 155 +++++----- .../__tests__/DBListBarChart.test.tsx | 135 +++++---- .../__tests__/DBNumberChart.test.tsx | 266 +++++++++-------- .../components/__tests__/DBPieChart.test.tsx | 257 ++++++++-------- .../__tests__/DBRowDataPanel.test.ts | 221 ++++++++------ .../components/__tests__/DBTimeChart.test.tsx | 275 ++++++++++-------- .../__tests__/DBTraceWaterfallChart.test.tsx | 89 ++++-- .../NumberTileBackgroundChart.test.tsx | 31 +- .../__tests__/SourceSelect.test.tsx | 46 +-- .../components/__tests__/SourcesList.test.tsx | 119 ++++---- .../sourceFormPickerDropdowns.test.tsx | 29 +- .../__tests__/useAutoCompleteOptions.test.tsx | 75 +++-- .../__tests__/useAvailableMetricNames.test.ts | 4 +- .../hooks/__tests__/useChartConfig.test.tsx | 5 +- .../useOffsetPaginatedQuery.test.tsx | 12 +- scripts/ci/ratchet-baseline.json | 2 +- 26 files changed, 1273 insertions(+), 970 deletions(-) diff --git a/packages/app/package.json b/packages/app/package.json index c74acb3b20..bffd7ec0d4 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -14,7 +14,7 @@ "build:clickhouse": "NEXT_PUBLIC_IS_LOCAL_MODE=true NEXT_PUBLIC_CLICKHOUSE_BUILD=true next build --webpack && node scripts/prepare-clickhouse-build-export.js", "run:clickhouse": "test -d out && npx rimraf tmp && mkdir tmp && cp -r out tmp/clickstack && echo 'visit http://localhost:3000/clickstack to start' && npx serve tmp -l 3000 || echo 'run build:clickhouse first'", "start": "next start", - "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 534 && yarn run -T oxfmt --check '**/*.{ts,tsx,css,scss}'", + "lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 468 && yarn run -T oxfmt --check '**/*.{ts,tsx,css,scss}'", "lint:fix": "yarn run -T oxlint --fix && yarn run -T oxfmt '**/*.{ts,tsx,css,scss}'", "lint:styles": "stylelint **/*/*.{css,scss}", "ci:lint": "yarn lint && yarn tsc --noEmit && yarn lint:styles --quiet", diff --git a/packages/app/src/__tests__/SessionSidePanel.test.tsx b/packages/app/src/__tests__/SessionSidePanel.test.tsx index 5006b0c7bb..f61eff31e5 100644 --- a/packages/app/src/__tests__/SessionSidePanel.test.tsx +++ b/packages/app/src/__tests__/SessionSidePanel.test.tsx @@ -69,12 +69,8 @@ jest.mock('@mantine/notifications', () => { }; }); -const mockedCopy = copyTextToClipboard as jest.MockedFunction< - typeof copyTextToClipboard ->; -const mockedShow = notifications.show as jest.MockedFunction< - typeof notifications.show ->; +const mockedCopy = jest.mocked(copyTextToClipboard); +const mockedShow = jest.mocked(notifications.show); function setLocationHref(url: string) { const parsed = new URL(url, 'http://localhost'); diff --git a/packages/app/src/__tests__/Spotlights.test.tsx b/packages/app/src/__tests__/Spotlights.test.tsx index 0b8f012058..ae55cfb697 100644 --- a/packages/app/src/__tests__/Spotlights.test.tsx +++ b/packages/app/src/__tests__/Spotlights.test.tsx @@ -1,6 +1,8 @@ +import { DisplayType } from '@hyperdx/common-utils/dist/types'; import { spotlight } from '@mantine/spotlight'; import { act, renderHook, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { fromPartial } from '@total-typescript/shoehorn'; import { useDashboards } from '@/dashboard'; import { useSavedSearches } from '@/savedSearch'; @@ -30,8 +32,8 @@ jest.mock('next/router', () => ({ jest.mock('../savedSearch'); jest.mock('../dashboard'); -const mockUseSavedSearches = useSavedSearches as jest.Mock; -const mockUseDashboards = useDashboards as jest.Mock; +const mockUseSavedSearches = jest.mocked(useSavedSearches); +const mockUseDashboards = jest.mocked(useDashboards); describe('useSpotlightActions', () => { const mockSavedSearches = { @@ -42,7 +44,7 @@ describe('useSpotlightActions', () => { name: 'save template1', select: '', where: '200', - whereLanguage: 'lucene', + whereLanguage: 'lucene' as const, orderBy: '', source: '67c25aeee3b6d5e2f24437b3', tags: [], @@ -71,13 +73,13 @@ describe('useSpotlightActions', () => { { aggFn: 'count', aggCondition: '200', - aggConditionLanguage: 'lucene', + aggConditionLanguage: 'lucene' as const, valueExpression: '', }, ], where: '', - whereLanguage: 'lucene', - displayType: 'line', + whereLanguage: 'lucene' as const, + displayType: DisplayType.Line, granularity: 'auto', source: '67c25aeee3b6d5e2f24437b3', }, @@ -97,8 +99,8 @@ describe('useSpotlightActions', () => { beforeEach(() => { jest.clearAllMocks(); window.localStorage.clear(); - mockUseSavedSearches.mockReturnValue(mockSavedSearches); - mockUseDashboards.mockReturnValue(mockSavedDashboard); + mockUseSavedSearches.mockReturnValue(fromPartial(mockSavedSearches)); + mockUseDashboards.mockReturnValue(fromPartial(mockSavedDashboard)); }); it('saved searches and dashboards should be loaded', () => { const { result } = renderHook(() => useSpotlightActions()); diff --git a/packages/app/src/__tests__/dashboard.remote.test.ts b/packages/app/src/__tests__/dashboard.remote.test.ts index 9bbca37c5a..498bab00cb 100644 --- a/packages/app/src/__tests__/dashboard.remote.test.ts +++ b/packages/app/src/__tests__/dashboard.remote.test.ts @@ -38,6 +38,7 @@ jest.mock('@tanstack/react-query', () => ({ jest.mock('@/utils', () => ({ hashCode: jest.fn(() => 0) })); import { LEGACY_CHART_PALETTE_TOKEN_MAP } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import { hdxServer } from '@/api'; import { @@ -47,7 +48,7 @@ import { useUpdateDashboard, } from '@/dashboard'; -const hdxServerMock = hdxServer as jest.Mock; +const hdxServerMock = jest.mocked(hdxServer); const LEGACY_TO_HUE_CASES = Object.entries(LEGACY_CHART_PALETTE_TOKEN_MAP); @@ -61,9 +62,11 @@ const remoteDashboardWithTileColor = (color: unknown) => [ ]; const setRemotePayload = (payload: unknown) => { - hdxServerMock.mockReturnValue({ - json: jest.fn().mockResolvedValue(payload), - }); + hdxServerMock.mockReturnValue( + fromPartial({ + json: jest.fn().mockResolvedValue(payload), + }), + ); }; beforeEach(() => { @@ -145,9 +148,11 @@ describe('useCreateDashboard / useUpdateDashboard write-time normalization', () beforeEach(() => { // hdxServer is invoked as `hdxServer(url, opts).json()` for POST // but as `hdxServer(url, opts)` for PATCH; mock to handle both. - hdxServerMock.mockReturnValue({ - json: jest.fn().mockResolvedValue({ id: 'a' }), - }); + hdxServerMock.mockReturnValue( + fromPartial({ + json: jest.fn().mockResolvedValue({ id: 'a' }), + }), + ); }); it('rewrites legacy chart-N to hue tokens before POST in useCreateDashboard', async () => { @@ -192,10 +197,21 @@ describe('useCreateDashboard / useUpdateDashboard write-time normalization', () tags: [], }); - const call = hdxServerMock.mock.calls[0]; - expect(call[1].json.tiles[0].config).toMatchObject({ - color: 'chart-future-magenta', - }); + expect(hdxServerMock).toHaveBeenNthCalledWith( + 1, + 'dashboards', + expect.objectContaining({ + json: expect.objectContaining({ + tiles: [ + expect.objectContaining({ + config: expect.objectContaining({ + color: 'chart-future-magenta', + }), + }), + ], + }), + }), + ); }); it('rewrites legacy chart-N to hue tokens before PATCH in useUpdateDashboard', async () => { @@ -236,8 +252,17 @@ describe('useCreateDashboard / useUpdateDashboard write-time normalization', () ], }); - const call = hdxServerMock.mock.calls[0]; - expect(call[1].json.tiles[0].config).toEqual({ color: 'chart-orange' }); + expect(hdxServerMock).toHaveBeenNthCalledWith( + 1, + 'dashboards/a', + expect.objectContaining({ + json: expect.objectContaining({ + tiles: [ + expect.objectContaining({ config: { color: 'chart-orange' } }), + ], + }), + }), + ); }); }); diff --git a/packages/app/src/__tests__/source.test.ts b/packages/app/src/__tests__/source.test.ts index fbc43e78ee..0636d18f1a 100644 --- a/packages/app/src/__tests__/source.test.ts +++ b/packages/app/src/__tests__/source.test.ts @@ -9,6 +9,7 @@ import { } from '@hyperdx/common-utils/dist/types'; import { notifications } from '@mantine/notifications'; import { renderHook } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import { getBuilderValueColumnCount, @@ -318,19 +319,21 @@ describe('useUpdateSource', () => { }); describe('useSources validation notifications', () => { - const mockUseQuery = useQuery as jest.Mock; - const mockHdxServer = hdxServer as jest.Mock; - const mockShow = notifications.show as jest.Mock; + const mockUseQuery = jest.mocked(useQuery); + const mockHdxServer = jest.mocked(hdxServer); + const mockShow = jest.mocked(notifications.show); beforeEach(() => { jest.clearAllMocks(); }); it('reuses the same notification id for repeated validation errors', async () => { - let capturedQueryFn: (() => Promise) | undefined; + let capturedQueryFn: (() => unknown) | undefined; mockUseQuery.mockImplementation(({ queryFn }) => { - capturedQueryFn = queryFn; - return { data: [] }; + if (typeof queryFn === 'function') { + capturedQueryFn = () => queryFn(fromPartial({})); + } + return fromPartial({ data: [] }); }); const invalidSource = { @@ -344,9 +347,11 @@ describe('useSources validation notifications', () => { serviceNameExpression: 42, }; - mockHdxServer.mockReturnValue({ - json: jest.fn().mockResolvedValue([invalidSource]), - }); + mockHdxServer.mockReturnValue( + fromPartial({ + json: jest.fn().mockResolvedValue([invalidSource]), + }), + ); useSources(); expect(capturedQueryFn).toBeDefined(); @@ -411,11 +416,11 @@ function makeRawSqlConfig( } describe('useSingleSeriesNumberFormat', () => { - const mockUseQuery = useQuery as jest.Mock; + const mockUseQuery = jest.mocked(useQuery); beforeEach(() => { jest.clearAllMocks(); - mockUseQuery.mockReturnValue({ data: TRACE_SOURCE }); + mockUseQuery.mockReturnValue(fromPartial({ data: TRACE_SOURCE })); }); it.each<{ @@ -519,14 +524,14 @@ describe('useSingleSeriesNumberFormat', () => { }); describe('useChartNumberFormats', () => { - const mockUseQuery = useQuery as jest.Mock; + const mockUseQuery = jest.mocked(useQuery); const META_A = { name: 'col_a', type: 'Float64' } as ColumnMetaType; const META_B = { name: 'col_b', type: 'Float64' } as ColumnMetaType; beforeEach(() => { jest.clearAllMocks(); - mockUseQuery.mockReturnValue({ data: TRACE_SOURCE }); + mockUseQuery.mockReturnValue(fromPartial({ data: TRACE_SOURCE })); }); // --- chartFormat resolution --- diff --git a/packages/app/src/components/ServiceMap/__tests__/utils.test.ts b/packages/app/src/components/ServiceMap/__tests__/utils.test.ts index 2523fb7ed8..819857ed40 100644 --- a/packages/app/src/components/ServiceMap/__tests__/utils.test.ts +++ b/packages/app/src/components/ServiceMap/__tests__/utils.test.ts @@ -1,5 +1,6 @@ import router from 'next/router'; import { SourceKind, TTraceSource } from '@hyperdx/common-utils/dist/types'; +import { fromPartial } from '@total-typescript/shoehorn'; import { buildServiceMapErrorWhere, @@ -68,6 +69,15 @@ describe('navigateToTraceSearch', () => { jest.clearAllMocks(); }); + // router.push accepts a UrlObject too; navigateToTraceSearch always passes a string. + function getPushedUrl(): string { + const callArg = jest.mocked(router.push).mock.calls[0]?.[0]; + if (typeof callArg !== 'string') { + throw new Error('Expected router.push to be called with a string URL'); + } + return callArg; + } + it('should navigate to search page with correct query parameters', () => { const dateRange: [Date, Date] = [ new Date('2024-01-15T10:00:00.000Z'), @@ -82,7 +92,7 @@ describe('navigateToTraceSearch', () => { expect(router.push).toHaveBeenCalledTimes(1); - const callArg = (router.push as jest.Mock).mock.calls[0][0]; + const callArg = getPushedUrl(); expect(callArg).toContain('/search?'); // Parse query params @@ -109,7 +119,7 @@ describe('navigateToTraceSearch', () => { where: 'status_code = 500', }); - const callArg = (router.push as jest.Mock).mock.calls[0][0]; + const callArg = getPushedUrl(); const url = new URL(callArg, 'http://localhost'); const params = url.searchParams; @@ -132,7 +142,7 @@ describe('navigateToTraceSearch', () => { where: complexWhere, }); - const callArg = (router.push as jest.Mock).mock.calls[0][0]; + const callArg = getPushedUrl(); const url = new URL(callArg, 'http://localhost'); const params = url.searchParams; @@ -153,7 +163,7 @@ describe('navigateToTraceSearch', () => { where: whereWithSpecialChars, }); - const callArg = (router.push as jest.Mock).mock.calls[0][0]; + const callArg = getPushedUrl(); const url = new URL(callArg, 'http://localhost'); const params = url.searchParams; @@ -649,7 +659,7 @@ describe('getNodeSize', () => { }); describe('deriveDisplayMetrics', () => { - const source = { durationPrecision: 9 } as unknown as TTraceSource; + const source = fromPartial({ durationPrecision: 9 }); const oneHour: [Date, Date] = [ new Date('2024-01-01T00:00:00.000Z'), new Date('2024-01-01T01:00:00.000Z'), diff --git a/packages/app/src/components/TimelineChart/__tests__/TimelineMinimap.test.tsx b/packages/app/src/components/TimelineChart/__tests__/TimelineMinimap.test.tsx index 9642c2cfcc..c8679114fa 100644 --- a/packages/app/src/components/TimelineChart/__tests__/TimelineMinimap.test.tsx +++ b/packages/app/src/components/TimelineChart/__tests__/TimelineMinimap.test.tsx @@ -139,7 +139,7 @@ describe('TimelineMinimap', () => { fireEvent.pointerUp(minimap, { clientX: 600, pointerId: 1 }); expect(controller.zoomToRange).toHaveBeenCalledTimes(1); - const [start, end] = (controller.zoomToRange as jest.Mock).mock.calls[0]; + const [start, end] = jest.mocked(controller.zoomToRange).mock.calls[0]; expect(start).toBeCloseTo(0.2, 5); expect(end).toBeCloseTo(0.6, 5); }); @@ -158,9 +158,10 @@ describe('TimelineMinimap', () => { fireEvent.pointerMove(minimap, { clientX: 475, pointerId: 1 }); expect(controller.panToOffset).toHaveBeenCalled(); - const lastCall = (controller.panToOffset as jest.Mock).mock.calls.at(-1); + const lastCall = jest.mocked(controller.panToOffset).mock.calls.at(-1); // moved +0.1 frac → offset 0.25 -> ~0.35 - expect(lastCall[0]).toBeCloseTo(0.35, 5); + expect(lastCall).toBeDefined(); + expect(lastCall?.[0]).toBeCloseTo(0.35, 5); expect(controller.zoomToRange).not.toHaveBeenCalled(); }); @@ -178,9 +179,10 @@ describe('TimelineMinimap', () => { fireEvent.pointerMove(minimap, { clientX: 700, pointerId: 1 }); expect(controller.zoomToRange).toHaveBeenCalled(); - const lastCall = (controller.zoomToRange as jest.Mock).mock.calls.at(-1); - expect(lastCall[0]).toBeCloseTo(0.25, 5); // start unchanged - expect(lastCall[1]).toBeCloseTo(0.7, 5); // end pushed to 0.7 + const lastCall = jest.mocked(controller.zoomToRange).mock.calls.at(-1); + expect(lastCall).toBeDefined(); + expect(lastCall?.[0]).toBeCloseTo(0.25, 5); // start unchanged + expect(lastCall?.[1]).toBeCloseTo(0.7, 5); // end pushed to 0.7 }); it('double-click resets when zoomed', () => { diff --git a/packages/app/src/components/__tests__/ActiveFilterPills.test.tsx b/packages/app/src/components/__tests__/ActiveFilterPills.test.tsx index 7437030818..e8a9fe1d70 100644 --- a/packages/app/src/components/__tests__/ActiveFilterPills.test.tsx +++ b/packages/app/src/components/__tests__/ActiveFilterPills.test.tsx @@ -1,6 +1,7 @@ import type { BuilderChartConfigWithDateRange } from '@hyperdx/common-utils/dist/types'; import { act, fireEvent, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { fromPartial } from '@total-typescript/shoehorn'; import { ActiveFilterPills } from '@/components/ActiveFilterPills'; import { useGetKeyValues } from '@/hooks/useMetadata'; @@ -25,7 +26,7 @@ jest.mock('@/useFormatTime', () => ({ useFormatTime: () => (value: unknown) => `formatted(${String(value)})`, })); -const mockedUseGetKeyValues = useGetKeyValues as jest.Mock; +const mockedUseGetKeyValues = jest.mocked(useGetKeyValues); // Mantine's Combobox calls scrollIntoView when its dropdown opens; jsdom lacks // it. jsdom also has no layout, so portaled options compute as "hidden" and @@ -71,7 +72,9 @@ function renderPills(searchFilters: FilterStateHook) { describe('ActiveFilterPills', () => { beforeEach(() => { jest.useFakeTimers(); - mockedUseGetKeyValues.mockReturnValue({ data: [], isFetching: false }); + mockedUseGetKeyValues.mockReturnValue( + fromPartial({ data: [], isFetching: false }), + ); }); afterEach(() => { jest.useRealTimers(); @@ -557,16 +560,19 @@ describe('ActiveFilterPills', () => { expect(mockedUseGetKeyValues).toHaveBeenCalled(); const { chartConfig: passedConfig } = mockedUseGetKeyValues.mock.calls[0][0]; - expect(passedConfig.where).toBe(''); - expect(passedConfig.filters).toEqual([]); + expect(passedConfig).toBeDefined(); + expect(passedConfig?.where).toBe(''); + expect(passedConfig?.filters).toEqual([]); }); it('shows a value picker populated from useGetKeyValues', async () => { jest.useRealTimers(); - mockedUseGetKeyValues.mockReturnValue({ - data: [{ key: 'status', value: ['200', '404', '500'] }], - isFetching: false, - }); + mockedUseGetKeyValues.mockReturnValue( + fromPartial({ + data: [{ key: 'status', value: ['200', '404', '500'] }], + isFetching: false, + }), + ); const user = userEvent.setup(); const searchFilters = makeSearchFilters({ status: { @@ -589,10 +595,12 @@ describe('ActiveFilterPills', () => { it('replaces the value from the menu, preserving include polarity', async () => { jest.useRealTimers(); - mockedUseGetKeyValues.mockReturnValue({ - data: [{ key: 'status', value: ['200', '404', '500'] }], - isFetching: false, - }); + mockedUseGetKeyValues.mockReturnValue( + fromPartial({ + data: [{ key: 'status', value: ['200', '404', '500'] }], + isFetching: false, + }), + ); const user = userEvent.setup(); const searchFilters = makeSearchFilters({ status: { @@ -618,10 +626,12 @@ describe('ActiveFilterPills', () => { it('submits the highlighted option when navigating with the keyboard and pressing Enter', async () => { jest.useRealTimers(); - mockedUseGetKeyValues.mockReturnValue({ - data: [{ key: 'status', value: ['200', '404', '500'] }], - isFetching: false, - }); + mockedUseGetKeyValues.mockReturnValue( + fromPartial({ + data: [{ key: 'status', value: ['200', '404', '500'] }], + isFetching: false, + }), + ); const user = userEvent.setup(); const searchFilters = makeSearchFilters({ status: { @@ -649,10 +659,12 @@ describe('ActiveFilterPills', () => { it('replaces with a free-typed value not in the suggestion list', async () => { jest.useRealTimers(); - mockedUseGetKeyValues.mockReturnValue({ - data: [{ key: 'status', value: ['200', '404', '500'] }], - isFetching: false, - }); + mockedUseGetKeyValues.mockReturnValue( + fromPartial({ + data: [{ key: 'status', value: ['200', '404', '500'] }], + isFetching: false, + }), + ); const user = userEvent.setup(); const searchFilters = makeSearchFilters({ status: { @@ -677,10 +689,12 @@ describe('ActiveFilterPills', () => { it('replaces the value from the menu, preserving exclude polarity', async () => { jest.useRealTimers(); - mockedUseGetKeyValues.mockReturnValue({ - data: [{ key: 'status', value: ['500', '502', '503'] }], - isFetching: false, - }); + mockedUseGetKeyValues.mockReturnValue( + fromPartial({ + data: [{ key: 'status', value: ['500', '502', '503'] }], + isFetching: false, + }), + ); const user = userEvent.setup(); const searchFilters = makeSearchFilters({ status: { diff --git a/packages/app/src/components/__tests__/DBBarChart.test.tsx b/packages/app/src/components/__tests__/DBBarChart.test.tsx index 581349c49a..b40c814b26 100644 --- a/packages/app/src/components/__tests__/DBBarChart.test.tsx +++ b/packages/app/src/components/__tests__/DBBarChart.test.tsx @@ -1,4 +1,5 @@ import { screen } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import DateRangeIndicator from '@/components/charts/DateRangeIndicator'; import { DBBarChart } from '@/components/DBBarChart'; @@ -32,7 +33,7 @@ jest.mock('../MaterializedViews/MVOptimizationIndicator', () => jest.mock('../charts/DateRangeIndicator', () => jest.fn(() => null)); describe('DBBarChart', () => { - const mockUseQueriedChartConfig = useQueriedChartConfig as jest.Mock; + const mockUseQueriedChartConfig = jest.mocked(useQueriedChartConfig); const baseTestConfig = { dateRange: [new Date(), new Date()] as [Date, Date], @@ -46,25 +47,29 @@ describe('DBBarChart', () => { beforeEach(() => { jest.clearAllMocks(); - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [{ test1: 1234, test2: 5678 }], - meta: [ - { name: 'test1', type: 'UInt64' }, - { name: 'test2', type: 'UInt64' }, - ], - }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [{ test1: 1234, test2: 5678 }], + meta: [ + { name: 'test1', type: 'UInt64' }, + { name: 'test2', type: 'UInt64' }, + ], + }, + isLoading: false, + isError: false, + }), + ); }); it('handles loading state correctly', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: undefined, - isLoading: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: undefined, + isLoading: true, + isError: false, + }), + ); renderWithMantine(); expect(screen.getByText('Loading Chart Data...')).toBeInTheDocument(); @@ -83,12 +88,14 @@ describe('DBBarChart', () => { }; it('pulses while a refetch is showing the previous result', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: groupedData, - isLoading: false, - isPlaceholderData: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: groupedData, + isLoading: false, + isPlaceholderData: true, + isError: false, + }), + ); renderWithMantine(); expect( @@ -99,12 +106,14 @@ describe('DBBarChart', () => { }); it('does not pulse once fresh data has loaded', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: groupedData, - isLoading: false, - isPlaceholderData: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: groupedData, + isLoading: false, + isPlaceholderData: false, + isError: false, + }), + ); renderWithMantine(); expect( @@ -115,12 +124,14 @@ describe('DBBarChart', () => { }); it('shows loading instead of the stale empty result during a refetch', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [], meta: groupedData.meta }, - isLoading: false, - isPlaceholderData: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [], meta: groupedData.meta }, + isLoading: false, + isPlaceholderData: true, + isError: false, + }), + ); renderWithMantine(); const loadingState = screen.getByText('Loading Chart Data...'); @@ -132,29 +143,33 @@ describe('DBBarChart', () => { }); it('handles error state correctly', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: undefined, - isLoading: false, - isError: true, - error: new Error('Test error'), - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: undefined, + isLoading: false, + isError: true, + error: new Error('Test error'), + }), + ); renderWithMantine(); expect(screen.getByText(/Error loading chart/)).toBeInTheDocument(); }); it('handles empty state correctly', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [], - meta: [ - { name: 'status', type: 'String' }, - { name: 'count', type: 'UInt64' }, - ], - }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [], + meta: [ + { name: 'status', type: 'String' }, + { name: 'count', type: 'UInt64' }, + ], + }, + isLoading: false, + isError: false, + }), + ); renderWithMantine(); expect( @@ -170,21 +185,23 @@ describe('DBBarChart', () => { }); it('should render bar chart with grouped data', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [ - { status: 'success', count: 100 }, - { status: 'error', count: 50 }, - { status: 'timeout', count: 25 }, - ], - meta: [ - { name: 'status', type: 'String' }, - { name: 'count', type: 'UInt64' }, - ], - }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [ + { status: 'success', count: 100 }, + { status: 'error', count: 50 }, + { status: 'timeout', count: 25 }, + ], + meta: [ + { name: 'status', type: 'String' }, + { name: 'count', type: 'UInt64' }, + ], + }, + isLoading: false, + isError: false, + }), + ); renderWithMantine(); expect(screen.getByTestId('bar-chart-container')).toBeInTheDocument(); @@ -192,9 +209,11 @@ describe('DBBarChart', () => { it('passes the same config to useMVOptimizationExplanation, useQueriedChartConfig, and MVOptimizationIndicator', () => { // Mock useSource to return a source so MVOptimizationIndicator is rendered - jest.mocked(useSource).mockReturnValue({ - data: { id: 'test-source', name: 'Test Source' }, - } as any); + jest.mocked(useSource).mockReturnValue( + fromPartial({ + data: { id: 'test-source', name: 'Test Source' }, + }), + ); renderWithMantine(); @@ -231,25 +250,27 @@ describe('DBBarChart', () => { }; // Mock useMVOptimizationExplanation to return an optimized config with aligned date range - jest.mocked(useMVOptimizationExplanation).mockReturnValue({ - data: { - optimizedConfig: { - ...config, - dateRange: [alignedStartDate, alignedEndDate] as [Date, Date], - }, - explanations: [ - { - success: true, - mvConfig: { - minGranularity: '1 minute', - tableName: 'metrics_rollup_1m', - }, + jest.mocked(useMVOptimizationExplanation).mockReturnValue( + fromPartial({ + data: { + optimizedConfig: { + ...config, + dateRange: [alignedStartDate, alignedEndDate] as [Date, Date], }, - ], - }, - isLoading: false, - isPlaceholderData: false, - } as any); + explanations: [ + { + success: true, + mvConfig: { + minGranularity: '1 minute', + tableName: 'metrics_rollup_1m', + }, + }, + ], + }, + isLoading: false, + isPlaceholderData: false, + }), + ); renderWithMantine(); @@ -272,14 +293,16 @@ describe('DBBarChart', () => { it('does not render DateRangeIndicator when MV optimization has no optimized date range', () => { // Mock useMVOptimizationExplanation to return data without an optimized config - jest.mocked(useMVOptimizationExplanation).mockReturnValue({ - data: { - optimizedConfig: undefined, - explanations: [], - }, - isLoading: false, - isPlaceholderData: false, - } as any); + jest.mocked(useMVOptimizationExplanation).mockReturnValue( + fromPartial({ + data: { + optimizedConfig: undefined, + explanations: [], + }, + isLoading: false, + isPlaceholderData: false, + }), + ); renderWithMantine(); diff --git a/packages/app/src/components/__tests__/DBDeltaChart.test.tsx b/packages/app/src/components/__tests__/DBDeltaChart.test.tsx index 6f207e2fb5..0f17522e69 100644 --- a/packages/app/src/components/__tests__/DBDeltaChart.test.tsx +++ b/packages/app/src/components/__tests__/DBDeltaChart.test.tsx @@ -1,9 +1,13 @@ import React from 'react'; +import type { TableMetadata } from '@hyperdx/common-utils/dist/core/metadata'; +import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; import { + BuilderChartConfig, BuilderChartConfigWithDateRange, Filter, } from '@hyperdx/common-utils/dist/types'; import { screen } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import DBDeltaChart from '@/components/DBDeltaChart'; import { useQueriedChartConfig } from '@/hooks/useChartConfig'; @@ -31,8 +35,25 @@ jest.mock('../PropertyComparisonChart', () => ({ ), })); -const mockUseQueriedChartConfig = useQueriedChartConfig as jest.Mock; -const mockUseTableMetadata = useTableMetadata as jest.Mock; +const mockUseQueriedChartConfig = jest.mocked(useQueriedChartConfig); +const mockUseTableMetadata = jest.mocked(useTableMetadata); + +function mockTableMetadata( + data: Pick | undefined, +) { + mockUseTableMetadata.mockReturnValue( + fromPartial({ data: data && fromPartial(data), isLoading: false }), + ); +} + +// DBDeltaChart only issues builder queries; narrowing exposes `with`/`filters`. +function getBuilderConfig(callIndex: number) { + const config = mockUseQueriedChartConfig.mock.calls[callIndex]?.[0]; + if (config == null || !isBuilderChartConfig(config)) { + throw new Error(`Expected call ${callIndex} to use a builder chart config`); + } + return config; +} // Sentinel filter on baseConfig so the allSpans assertion can prove // the branch passes user-supplied filters through unchanged. Without @@ -70,15 +91,14 @@ function renderChart( describe('DBDeltaChart', () => { beforeEach(() => { jest.clearAllMocks(); - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [], meta: [] }, - error: undefined, - isLoading: false, - }); - mockUseTableMetadata.mockReturnValue({ - data: { engine: 'MergeTree', isPointerTable: false }, - isLoading: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [], meta: [] }, + error: undefined, + isLoading: false, + }), + ); + mockTableMetadata({ engine: 'MergeTree', isPointerTable: false }); }); describe('distribution mode (no heatmap selection)', () => { @@ -133,9 +153,9 @@ describe('DBDeltaChart', () => { // Sanity: the outlier branch DOES inject extra filters built from // the (defaulted-to-zero) coords, so its filters array is strictly // longer than baseConfig.filters. - const outlierConfig = calls[0][0]; - expect(outlierConfig.filters.length).toBeGreaterThan(1); - expect(outlierConfig.filters[0]).toEqual(sentinelFilter); + const outlierConfig = getBuilderConfig(0); + expect(outlierConfig.filters?.length).toBeGreaterThan(1); + expect(outlierConfig.filters?.[0]).toEqual(sentinelFilter); }); }); @@ -192,14 +212,14 @@ describe('DBDeltaChart', () => { describe('selection queries by table engine', () => { const selection = { xMin: 1, xMax: 2, yMin: 1, yMax: 2 }; - const conditions = (config: BuilderChartConfigWithDateRange) => + const conditions = (config: Pick) => (config.filters ?? []).map(f => ('condition' in f ? f.condition : '')); it('uses the PartIds prefetch hint on local MergeTree tables', () => { renderChart(selection); - const [[outlierConfig], [inlierConfig]] = - mockUseQueriedChartConfig.mock.calls; + const outlierConfig = getBuilderConfig(0); + const inlierConfig = getBuilderConfig(1); for (const config of [outlierConfig, inlierConfig]) { expect(config.with?.map((cte: { name: string }) => cte.name)).toEqual([ 'PartIds', @@ -213,8 +233,8 @@ describe('DBDeltaChart', () => { it('uses plain IN for the aggregated-timestamps subquery on local MergeTree tables', () => { renderChart({ ...selection, valueExpr: 'count()' }); - const [[outlierConfig], [inlierConfig]] = - mockUseQueriedChartConfig.mock.calls; + const outlierConfig = getBuilderConfig(0); + const inlierConfig = getBuilderConfig(1); expect(conditions(outlierConfig)).toContain( 'Timestamp IN (SELECT Timestamp FROM AggregatedTimestamps)', ); @@ -224,14 +244,11 @@ describe('DBDeltaChart', () => { }); it('skips the PartIds hint on Distributed tables', () => { - mockUseTableMetadata.mockReturnValue({ - data: { engine: 'MergeTree', isPointerTable: true }, - isLoading: false, - }); + mockTableMetadata({ engine: 'MergeTree', isPointerTable: true }); renderChart(selection); - const [[outlierConfig], [inlierConfig]] = - mockUseQueriedChartConfig.mock.calls; + const outlierConfig = getBuilderConfig(0); + const inlierConfig = getBuilderConfig(1); for (const config of [outlierConfig, inlierConfig]) { expect(config.with).toBeUndefined(); expect(conditions(config).join(' ')).not.toContain('_part'); @@ -239,14 +256,11 @@ describe('DBDeltaChart', () => { }); it('uses GLOBAL IN for the aggregated-timestamps subquery on Distributed tables', () => { - mockUseTableMetadata.mockReturnValue({ - data: { engine: 'MergeTree', isPointerTable: true }, - isLoading: false, - }); + mockTableMetadata({ engine: 'MergeTree', isPointerTable: true }); renderChart({ ...selection, valueExpr: 'count()' }); - const [[outlierConfig], [inlierConfig]] = - mockUseQueriedChartConfig.mock.calls; + const outlierConfig = getBuilderConfig(0); + const inlierConfig = getBuilderConfig(1); expect( outlierConfig.with?.map((cte: { name: string }) => cte.name), ).toEqual(['AggregatedTimestamps']); @@ -259,10 +273,9 @@ describe('DBDeltaChart', () => { }); it('waits for table metadata before running selection queries', () => { - mockUseTableMetadata.mockReturnValue({ - data: undefined, - isLoading: true, - }); + mockUseTableMetadata.mockReturnValue( + fromPartial({ data: undefined, isLoading: true }), + ); renderChart(selection); const [outlierCall, inlierCall] = mockUseQueriedChartConfig.mock.calls; @@ -271,27 +284,21 @@ describe('DBDeltaChart', () => { }); it('falls back to the hint-free query when table metadata is unavailable', () => { - mockUseTableMetadata.mockReturnValue({ - data: undefined, - isLoading: false, - }); + mockTableMetadata(undefined); renderChart(selection); - const [[outlierConfig, outlierOptions]] = - mockUseQueriedChartConfig.mock.calls; + const outlierOptions = mockUseQueriedChartConfig.mock.calls[0][1]; + const outlierConfig = getBuilderConfig(0); expect(outlierOptions).toMatchObject({ enabled: true }); expect(outlierConfig.with).toBeUndefined(); }); it('uses GLOBAL IN for aggregate selections when table metadata is unavailable', () => { - mockUseTableMetadata.mockReturnValue({ - data: undefined, - isLoading: false, - }); + mockTableMetadata(undefined); renderChart({ ...selection, valueExpr: 'count()' }); - const [[outlierConfig], [inlierConfig]] = - mockUseQueriedChartConfig.mock.calls; + const outlierConfig = getBuilderConfig(0); + const inlierConfig = getBuilderConfig(1); expect(conditions(outlierConfig)).toContain( 'Timestamp GLOBAL IN (SELECT Timestamp FROM AggregatedTimestamps)', ); diff --git a/packages/app/src/components/__tests__/DBHistogramChart.test.tsx b/packages/app/src/components/__tests__/DBHistogramChart.test.tsx index 2ca9c63e10..27b3495f59 100644 --- a/packages/app/src/components/__tests__/DBHistogramChart.test.tsx +++ b/packages/app/src/components/__tests__/DBHistogramChart.test.tsx @@ -1,5 +1,6 @@ import React from 'react'; import { screen } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import DateRangeIndicator from '@/components/charts/DateRangeIndicator'; import DBHistogramChart, { @@ -36,7 +37,7 @@ jest.mock('../MaterializedViews/MVOptimizationIndicator', () => jest.mock('../charts/DateRangeIndicator', () => jest.fn(() => null)); describe('DBHistogramChart', () => { - const mockUseQueriedChartConfig = useQueriedChartConfig as jest.Mock; + const mockUseQueriedChartConfig = jest.mocked(useQueriedChartConfig); const baseTestConfig = { dateRange: [new Date(), new Date()] as [Date, Date], @@ -50,21 +51,25 @@ describe('DBHistogramChart', () => { beforeEach(() => { jest.clearAllMocks(); - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [{ bucket: '0-10', count: 5 }], - meta: [], - }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [{ bucket: '0-10', count: 5 }], + meta: [], + }, + isLoading: false, + isError: false, + }), + ); }); it('passes the same config to useMVOptimizationExplanation, useQueriedChartConfig, and MVOptimizationIndicator', () => { // Mock useSource to return a source so MVOptimizationIndicator is rendered - jest.mocked(useSource).mockReturnValue({ - data: { id: 'test-source', name: 'Test Source' }, - } as any); + jest.mocked(useSource).mockReturnValue( + fromPartial({ + data: { id: 'test-source', name: 'Test Source' }, + }), + ); renderWithMantine(); @@ -101,25 +106,27 @@ describe('DBHistogramChart', () => { }; // Mock useMVOptimizationExplanation to return an optimized config with aligned date range - jest.mocked(useMVOptimizationExplanation).mockReturnValue({ - data: { - optimizedConfig: { - ...config, - dateRange: [alignedStartDate, alignedEndDate] as [Date, Date], - }, - explanations: [ - { - success: true, - mvConfig: { - minGranularity: '1 minute', - tableName: 'metrics_rollup_1m', - }, + jest.mocked(useMVOptimizationExplanation).mockReturnValue( + fromPartial({ + data: { + optimizedConfig: { + ...config, + dateRange: [alignedStartDate, alignedEndDate] as [Date, Date], }, - ], - }, - isLoading: false, - isPlaceholderData: false, - } as any); + explanations: [ + { + success: true, + mvConfig: { + minGranularity: '1 minute', + tableName: 'metrics_rollup_1m', + }, + }, + ], + }, + isLoading: false, + isPlaceholderData: false, + }), + ); renderWithMantine(); @@ -142,14 +149,16 @@ describe('DBHistogramChart', () => { it('does not render DateRangeIndicator when MV optimization has no optimized date range', () => { // Mock useMVOptimizationExplanation to return data without an optimized config - jest.mocked(useMVOptimizationExplanation).mockReturnValue({ - data: { - optimizedConfig: undefined, - explanations: [], - }, - isLoading: false, - isPlaceholderData: false, - } as any); + jest.mocked(useMVOptimizationExplanation).mockReturnValue( + fromPartial({ + data: { + optimizedConfig: undefined, + explanations: [], + }, + isLoading: false, + isPlaceholderData: false, + }), + ); renderWithMantine(); @@ -164,12 +173,14 @@ describe('DBHistogramChart', () => { it('keeps the previous histogram on screen and pulses it while a refresh loads', () => { // The new range is still loading behind the previous buckets. - mockUseQueriedChartConfig.mockReturnValue({ - data: buckets, - isLoading: true, - isPlaceholderData: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: buckets, + isLoading: true, + isPlaceholderData: true, + isError: false, + }), + ); renderWithMantine(); @@ -180,12 +191,14 @@ describe('DBHistogramChart', () => { }); it('does not pulse once fresh buckets load', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: buckets, - isLoading: false, - isPlaceholderData: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: buckets, + isLoading: false, + isPlaceholderData: false, + isError: false, + }), + ); renderWithMantine(); @@ -193,12 +206,14 @@ describe('DBHistogramChart', () => { }); it('shows loading instead of the stale empty result during a refetch', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [], meta: [] }, - isLoading: false, - isPlaceholderData: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [], meta: [] }, + isLoading: false, + isPlaceholderData: true, + isError: false, + }), + ); renderWithMantine(); @@ -207,12 +222,14 @@ describe('DBHistogramChart', () => { }); it('does not pulse a fresh empty result', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [], meta: [] }, - isLoading: false, - isPlaceholderData: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [], meta: [] }, + isLoading: false, + isPlaceholderData: false, + isError: false, + }), + ); renderWithMantine(); @@ -222,12 +239,14 @@ describe('DBHistogramChart', () => { }); it('shows the loading state before the first buckets arrive', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: undefined, - isLoading: true, - isPlaceholderData: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: undefined, + isLoading: true, + isPlaceholderData: false, + isError: false, + }), + ); renderWithMantine(); diff --git a/packages/app/src/components/__tests__/DBListBarChart.test.tsx b/packages/app/src/components/__tests__/DBListBarChart.test.tsx index 4d3548675b..62b688c2e2 100644 --- a/packages/app/src/components/__tests__/DBListBarChart.test.tsx +++ b/packages/app/src/components/__tests__/DBListBarChart.test.tsx @@ -1,5 +1,6 @@ import React from 'react'; import { screen } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import DateRangeIndicator from '@/components/charts/DateRangeIndicator'; import DBListBarChart from '@/components/DBListBarChart'; @@ -35,7 +36,7 @@ jest.mock('../MaterializedViews/MVOptimizationIndicator', () => jest.mock('../charts/DateRangeIndicator', () => jest.fn(() => null)); describe('DBListBarChart', () => { - const mockUseQueriedChartConfig = useQueriedChartConfig as jest.Mock; + const mockUseQueriedChartConfig = jest.mocked(useQueriedChartConfig); const baseTestConfig = { dateRange: [new Date(), new Date()] as [Date, Date], @@ -49,18 +50,22 @@ describe('DBListBarChart', () => { beforeEach(() => { jest.clearAllMocks(); - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ group: 'test', value: 100 }] }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ group: 'test', value: 100 }] }, + isLoading: false, + isError: false, + }), + ); }); it('passes the same config to useMVOptimizationExplanation, useQueriedChartConfig, and MVOptimizationIndicator', () => { // Mock useSource to return a source so MVOptimizationIndicator is rendered - jest.mocked(useSource).mockReturnValue({ - data: { id: 'test-source', name: 'Test Source' }, - } as any); + jest.mocked(useSource).mockReturnValue( + fromPartial({ + data: { id: 'test-source', name: 'Test Source' }, + }), + ); renderWithMantine( { }; // Mock useMVOptimizationExplanation to return an optimized config with aligned date range - jest.mocked(useMVOptimizationExplanation).mockReturnValue({ - data: { - optimizedConfig: { - ...config, - dateRange: [alignedStartDate, alignedEndDate] as [Date, Date], - }, - explanations: [ - { - success: true, - mvConfig: { - minGranularity: '1 minute', - tableName: 'metrics_rollup_1m', - }, + jest.mocked(useMVOptimizationExplanation).mockReturnValue( + fromPartial({ + data: { + optimizedConfig: { + ...config, + dateRange: [alignedStartDate, alignedEndDate] as [Date, Date], }, - ], - }, - isLoading: false, - isPlaceholderData: false, - } as any); + explanations: [ + { + success: true, + mvConfig: { + minGranularity: '1 minute', + tableName: 'metrics_rollup_1m', + }, + }, + ], + }, + isLoading: false, + isPlaceholderData: false, + }), + ); renderWithMantine( { it('does not render DateRangeIndicator when MV optimization has no optimized date range', () => { // Mock useMVOptimizationExplanation to return data without an optimized config - jest.mocked(useMVOptimizationExplanation).mockReturnValue({ - data: { - optimizedConfig: undefined, - explanations: [], - }, - isLoading: false, - isPlaceholderData: false, - } as any); + jest.mocked(useMVOptimizationExplanation).mockReturnValue( + fromPartial({ + data: { + optimizedConfig: undefined, + explanations: [], + }, + isLoading: false, + isPlaceholderData: false, + }), + ); renderWithMantine( { ); it('pulses the previous bars while a refresh loads', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ group: 'checkout', value: 100 }] }, - isLoading: false, - isPlaceholderData: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ group: 'checkout', value: 100 }] }, + isLoading: false, + isPlaceholderData: true, + isError: false, + }), + ); renderChart(); @@ -197,12 +208,14 @@ describe('DBListBarChart', () => { }); it('does not pulse once fresh bars load', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ group: 'checkout', value: 100 }] }, - isLoading: false, - isPlaceholderData: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ group: 'checkout', value: 100 }] }, + isLoading: false, + isPlaceholderData: false, + isError: false, + }), + ); renderChart(); @@ -210,12 +223,14 @@ describe('DBListBarChart', () => { }); it('shows loading instead of the stale empty result during a refetch', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [] }, - isLoading: false, - isPlaceholderData: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [] }, + isLoading: false, + isPlaceholderData: true, + isError: false, + }), + ); renderChart(); @@ -224,12 +239,14 @@ describe('DBListBarChart', () => { }); it('does not pulse a fresh empty result', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [] }, - isLoading: false, - isPlaceholderData: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [] }, + isLoading: false, + isPlaceholderData: false, + isError: false, + }), + ); renderChart(); diff --git a/packages/app/src/components/__tests__/DBNumberChart.test.tsx b/packages/app/src/components/__tests__/DBNumberChart.test.tsx index 9f8de59227..6578cfbf72 100644 --- a/packages/app/src/components/__tests__/DBNumberChart.test.tsx +++ b/packages/app/src/components/__tests__/DBNumberChart.test.tsx @@ -1,6 +1,7 @@ import React from 'react'; import { DisplayType } from '@hyperdx/common-utils/dist/types'; import { act, screen } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import DateRangeIndicator from '@/components/charts/DateRangeIndicator'; import DBNumberChart from '@/components/DBNumberChart'; @@ -66,8 +67,8 @@ jest.mock('../NumberTileBackgroundChart', () => ({ })); describe('DBNumberChart', () => { - const mockUseQueriedChartConfig = useQueriedChartConfig as jest.Mock; - const mockFormatNumber = formatNumber as jest.Mock; + const mockUseQueriedChartConfig = jest.mocked(useQueriedChartConfig); + const mockFormatNumber = jest.mocked(formatNumber); const baseTestConfig = { dateRange: [new Date(), new Date()] as [Date, Date], @@ -81,15 +82,17 @@ describe('DBNumberChart', () => { beforeEach(() => { jest.clearAllMocks(); - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ value: 1234 }] }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ value: 1234 }] }, + isLoading: false, + isError: false, + }), + ); // Mock formatNumber to isolate just testing the chart component mockFormatNumber.mockImplementation((value, format) => { - if (!format) return value.toString(); + if (!format) return String(value); if (format.output === 'percent') return `${value}%`; if (format.output === 'currency') return `$${value}`; @@ -155,7 +158,7 @@ describe('DBNumberChart', () => { const [queriedConfig, options] = mockUseQueriedChartConfig.mock.calls[0]; expect(queriedConfig.numberFormat).toEqual(numberFormat); - expect(options.queryKeyPrefix).toBe('test'); + expect(options?.queryKeyPrefix).toBe('test'); }); it('displays formatted number in the UI', () => { @@ -173,11 +176,13 @@ describe('DBNumberChart', () => { }); it('handles zero values correctly', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ value: 0 }] }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ value: 0 }] }, + isLoading: false, + isError: false, + }), + ); const config = { ...baseTestConfig, @@ -192,22 +197,26 @@ describe('DBNumberChart', () => { }); it('displays NaN for null or undefined values', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ value: null }] }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ value: null }] }, + isLoading: false, + isError: false, + }), + ); renderWithMantine(); expect(screen.getByText('NaN')).toBeInTheDocument(); }); it('handles loading state correctly', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: undefined, - isLoading: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: undefined, + isLoading: true, + isError: false, + }), + ); renderWithMantine(); expect(screen.getByText('Loading Chart Data...')).toBeInTheDocument(); @@ -215,12 +224,14 @@ describe('DBNumberChart', () => { describe('refresh indicator', () => { it('pulses while a refetch is showing the previous value', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ value: 1234 }] }, - isLoading: false, - isPlaceholderData: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ value: 1234 }] }, + isLoading: false, + isPlaceholderData: true, + isError: false, + }), + ); renderWithMantine(); expect( @@ -231,12 +242,14 @@ describe('DBNumberChart', () => { it('pulses while still loading with a value on screen', () => { // useQueriedChartConfig's isLoading also covers the MV-optimization // check, which can be pending while a value is shown - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ value: 1234 }] }, - isLoading: true, - isPlaceholderData: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ value: 1234 }] }, + isLoading: true, + isPlaceholderData: false, + isError: false, + }), + ); renderWithMantine(); expect( @@ -245,12 +258,14 @@ describe('DBNumberChart', () => { }); it('does not pulse once the fresh value has loaded', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ value: 1234 }] }, - isLoading: false, - isPlaceholderData: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ value: 1234 }] }, + isLoading: false, + isPlaceholderData: false, + isError: false, + }), + ); renderWithMantine(); expect( @@ -259,12 +274,14 @@ describe('DBNumberChart', () => { }); it('shows loading instead of the stale empty result during a refetch', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [] }, - isLoading: false, - isPlaceholderData: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [] }, + isLoading: false, + isPlaceholderData: true, + isError: false, + }), + ); renderWithMantine(); expect(screen.getByText('Loading Chart Data...')).toBeInTheDocument(); @@ -273,12 +290,14 @@ describe('DBNumberChart', () => { }); it('handles error state correctly', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: undefined, - isLoading: false, - isError: true, - error: new Error('Test error'), - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: undefined, + isLoading: false, + isError: true, + error: new Error('Test error'), + }), + ); renderWithMantine(); expect(screen.getByText(/Error loading chart/)).toBeInTheDocument(); @@ -286,9 +305,11 @@ describe('DBNumberChart', () => { it('passes the same config to useMVOptimizationExplanation, useQueriedChartConfig, and MVOptimizationIndicator', () => { // Mock useSource to return a source so MVOptimizationIndicator is rendered - jest.mocked(useSource).mockReturnValue({ - data: { id: 'test-source', name: 'Test Source' }, - } as any); + jest.mocked(useSource).mockReturnValue( + fromPartial({ + data: { id: 'test-source', name: 'Test Source' }, + }), + ); renderWithMantine(); @@ -325,25 +346,27 @@ describe('DBNumberChart', () => { }; // Mock useMVOptimizationExplanation to return an optimized config with aligned date range - jest.mocked(useMVOptimizationExplanation).mockReturnValue({ - data: { - optimizedConfig: { - ...config, - dateRange: [alignedStartDate, alignedEndDate] as [Date, Date], - }, - explanations: [ - { - success: true, - mvConfig: { - minGranularity: '1 minute', - tableName: 'metrics_rollup_1m', - }, + jest.mocked(useMVOptimizationExplanation).mockReturnValue( + fromPartial({ + data: { + optimizedConfig: { + ...config, + dateRange: [alignedStartDate, alignedEndDate] as [Date, Date], }, - ], - }, - isLoading: false, - isPlaceholderData: false, - } as any); + explanations: [ + { + success: true, + mvConfig: { + minGranularity: '1 minute', + tableName: 'metrics_rollup_1m', + }, + }, + ], + }, + isLoading: false, + isPlaceholderData: false, + }), + ); renderWithMantine(); @@ -366,14 +389,16 @@ describe('DBNumberChart', () => { it('does not render DateRangeIndicator when MV optimization has no optimized date range', () => { // Mock useMVOptimizationExplanation to return data without an optimized config - jest.mocked(useMVOptimizationExplanation).mockReturnValue({ - data: { - optimizedConfig: undefined, - explanations: [], - }, - isLoading: false, - isPlaceholderData: false, - } as any); + jest.mocked(useMVOptimizationExplanation).mockReturnValue( + fromPartial({ + data: { + optimizedConfig: undefined, + explanations: [], + }, + isLoading: false, + isPlaceholderData: false, + }), + ); renderWithMantine(); @@ -382,7 +407,7 @@ describe('DBNumberChart', () => { }); describe('colorRules (conditional colors)', () => { - const mockGetColorFromCSSToken = getColorFromCSSToken as jest.Mock; + const mockGetColorFromCSSToken = jest.mocked(getColorFromCSSToken); beforeEach(() => { // Each test controls the data value independently @@ -390,11 +415,13 @@ describe('DBNumberChart', () => { }); function setDataValue(v: number) { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ value: v }] }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ value: v }] }, + isLoading: false, + isError: false, + }), + ); } it('uses static color when no rule matches (value 50, threshold ≥ 100)', () => { @@ -488,11 +515,13 @@ describe('DBNumberChart', () => { it('coerces string data values (ClickHouse UInt64) to numbers for rule evaluation', () => { // ClickHouse returns UInt64 as a JSON string when quote_64bit_integers is set - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ value: '1000' }] }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ value: '1000' }] }, + isLoading: false, + isError: false, + }), + ); mockFormatNumber.mockReturnValue('1000'); const config = { ...baseTestConfig, @@ -517,7 +546,7 @@ describe('DBNumberChart', () => { }); describe('color', () => { - const mockGetColorFromCSSToken = getColorFromCSSToken as jest.Mock; + const mockGetColorFromCSSToken = jest.mocked(getColorFromCSSToken); it('resolves a palette token through getColorFromCSSToken when config.color is set', () => { const config = { @@ -656,11 +685,13 @@ describe('DBNumberChart', () => { it('shrinks the font for a narrow tile so the value fits without overflow', () => { const restore = installGeometryMocks(120, 80); try { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [{ value: 1234567890 }] }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [{ value: 1234567890 }] }, + isLoading: false, + isError: false, + }), + ); renderWithMantine(); @@ -737,8 +768,7 @@ describe('DBNumberChart', () => { }); describe('background chart', () => { - const mockBackgroundChart = - NumberTileBackgroundChart as unknown as jest.Mock; + const mockBackgroundChart = jest.mocked(NumberTileBackgroundChart); it('renders the background sparkline when backgroundChart is configured', () => { const config = { @@ -789,11 +819,13 @@ describe('DBNumberChart', () => { ]; const setInstantRows = (rows: { series_name: string; value: number }[]) => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: rows, meta: instantMeta, rows: rows.length }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: rows, meta: instantMeta, rows: rows.length }, + isLoading: false, + isError: false, + }), + ); }; it("floors an auto granularity at the source's minimum", () => { @@ -854,15 +886,17 @@ describe('DBNumberChart', () => { }); it('does not warn for a non-PromQL config with several rows', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [{ value: 1 }, { value: 2 }], - meta: [{ name: 'value', type: 'Float64' }], - rows: 2, - }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [{ value: 1 }, { value: 2 }], + meta: [{ name: 'value', type: 'Float64' }], + rows: 2, + }, + isLoading: false, + isError: false, + }), + ); mockFormatNumber.mockReturnValue('1'); renderWithMantine(); diff --git a/packages/app/src/components/__tests__/DBPieChart.test.tsx b/packages/app/src/components/__tests__/DBPieChart.test.tsx index 1c51d38726..34f40f1538 100644 --- a/packages/app/src/components/__tests__/DBPieChart.test.tsx +++ b/packages/app/src/components/__tests__/DBPieChart.test.tsx @@ -1,5 +1,7 @@ +import { isPromqlChartConfig } from '@hyperdx/common-utils/dist/guards'; import { DisplayType, PromqlReducer } from '@hyperdx/common-utils/dist/types'; import { screen, within } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import DateRangeIndicator from '@/components/charts/DateRangeIndicator'; import { DBPieChart } from '@/components/DBPieChart'; @@ -36,7 +38,7 @@ jest.mock('../MaterializedViews/MVOptimizationIndicator', () => jest.mock('../charts/DateRangeIndicator', () => jest.fn(() => null)); describe('DBPieChart', () => { - const mockUseQueriedChartConfig = useQueriedChartConfig as jest.Mock; + const mockUseQueriedChartConfig = jest.mocked(useQueriedChartConfig); const baseTestConfig = { dateRange: [new Date(), new Date()] as [Date, Date], @@ -50,25 +52,29 @@ describe('DBPieChart', () => { beforeEach(() => { jest.clearAllMocks(); - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [{ test1: 1234, test2: 5678 }], - meta: [ - { name: 'test1', type: 'UInt64' }, - { name: 'test2', type: 'UInt64' }, - ], - }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [{ test1: 1234, test2: 5678 }], + meta: [ + { name: 'test1', type: 'UInt64' }, + { name: 'test2', type: 'UInt64' }, + ], + }, + isLoading: false, + isError: false, + }), + ); }); it('handles loading state correctly', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: undefined, - isLoading: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: undefined, + isLoading: true, + isError: false, + }), + ); renderWithMantine(); expect(screen.getByText('Loading Chart Data...')).toBeInTheDocument(); @@ -87,12 +93,14 @@ describe('DBPieChart', () => { }; it('pulses while a refetch is showing the previous result', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: groupedData, - isLoading: false, - isPlaceholderData: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: groupedData, + isLoading: false, + isPlaceholderData: true, + isError: false, + }), + ); renderWithMantine(); expect(screen.getByTestId('pie-chart-container')).toHaveClass( @@ -105,12 +113,14 @@ describe('DBPieChart', () => { }); it('does not pulse once fresh data has loaded', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: groupedData, - isLoading: false, - isPlaceholderData: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: groupedData, + isLoading: false, + isPlaceholderData: false, + isError: false, + }), + ); renderWithMantine(); expect(screen.getByTestId('pie-chart-container')).not.toHaveClass( @@ -119,12 +129,14 @@ describe('DBPieChart', () => { }); it('shows loading instead of the stale empty result during a refetch', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [], meta: groupedData.meta }, - isLoading: false, - isPlaceholderData: true, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [], meta: groupedData.meta }, + isLoading: false, + isPlaceholderData: true, + isError: false, + }), + ); renderWithMantine(); expect(screen.getByText('Loading Chart Data...')).toBeInTheDocument(); @@ -133,12 +145,14 @@ describe('DBPieChart', () => { }); it('handles error state correctly', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: undefined, - isLoading: false, - isError: true, - error: new Error('Test error'), - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: undefined, + isLoading: false, + isError: true, + error: new Error('Test error'), + }), + ); renderWithMantine(); expect(screen.getByText(/Error loading chart/)).toBeInTheDocument(); @@ -152,21 +166,23 @@ describe('DBPieChart', () => { }); it('should render pie chart legend with labels', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [ - { status: 'success', count: 100 }, - { status: 'error', count: 50 }, - { status: 'timeout', count: 25 }, - ], - meta: [ - { name: 'status', type: 'String' }, - { name: 'count', type: 'UInt64' }, - ], - }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [ + { status: 'success', count: 100 }, + { status: 'error', count: 50 }, + { status: 'timeout', count: 25 }, + ], + meta: [ + { name: 'status', type: 'String' }, + { name: 'count', type: 'UInt64' }, + ], + }, + isLoading: false, + isError: false, + }), + ); renderWithMantine(); const legend = screen.getByTestId('pie-chart-legend'); @@ -182,17 +198,19 @@ describe('DBPieChart', () => { count: 100 - i, })); - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: manyGroups, - meta: [ - { name: 'status', type: 'String' }, - { name: 'count', type: 'UInt64' }, - ], - }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: manyGroups, + meta: [ + { name: 'status', type: 'String' }, + { name: 'count', type: 'UInt64' }, + ], + }, + isLoading: false, + isError: false, + }), + ); renderWithMantine(); const legend = screen.getByTestId('pie-chart-legend'); @@ -204,9 +222,11 @@ describe('DBPieChart', () => { it('passes the same config to useMVOptimizationExplanation, useQueriedChartConfig, and MVOptimizationIndicator', () => { // Mock useSource to return a source so MVOptimizationIndicator is rendered - jest.mocked(useSource).mockReturnValue({ - data: { id: 'test-source', name: 'Test Source' }, - } as any); + jest.mocked(useSource).mockReturnValue( + fromPartial({ + data: { id: 'test-source', name: 'Test Source' }, + }), + ); renderWithMantine(); @@ -243,25 +263,27 @@ describe('DBPieChart', () => { }; // Mock useMVOptimizationExplanation to return an optimized config with aligned date range - jest.mocked(useMVOptimizationExplanation).mockReturnValue({ - data: { - optimizedConfig: { - ...config, - dateRange: [alignedStartDate, alignedEndDate] as [Date, Date], - }, - explanations: [ - { - success: true, - mvConfig: { - minGranularity: '1 minute', - tableName: 'metrics_rollup_1m', - }, + jest.mocked(useMVOptimizationExplanation).mockReturnValue( + fromPartial({ + data: { + optimizedConfig: { + ...config, + dateRange: [alignedStartDate, alignedEndDate] as [Date, Date], }, - ], - }, - isLoading: false, - isPlaceholderData: false, - } as any); + explanations: [ + { + success: true, + mvConfig: { + minGranularity: '1 minute', + tableName: 'metrics_rollup_1m', + }, + }, + ], + }, + isLoading: false, + isPlaceholderData: false, + }), + ); renderWithMantine(); @@ -284,14 +306,16 @@ describe('DBPieChart', () => { it('does not render DateRangeIndicator when MV optimization has no optimized date range', () => { // Mock useMVOptimizationExplanation to return data without an optimized config - jest.mocked(useMVOptimizationExplanation).mockReturnValue({ - data: { - optimizedConfig: undefined, - explanations: [], - }, - isLoading: false, - isPlaceholderData: false, - } as any); + jest.mocked(useMVOptimizationExplanation).mockReturnValue( + fromPartial({ + data: { + optimizedConfig: undefined, + explanations: [], + }, + isLoading: false, + isPlaceholderData: false, + }), + ); renderWithMantine(); @@ -316,9 +340,9 @@ describe('DBPieChart', () => { renderWithMantine(); const queriedConfig = mockUseQueriedChartConfig.mock.calls[0][0]; - expect(queriedConfig.promqlExpression).toEqual([ - { expression: 'up', reducer: PromqlReducer.LastNotNull }, - ]); + expect( + isPromqlChartConfig(queriedConfig) && queriedConfig.promqlExpression, + ).toEqual([{ expression: 'up', reducer: PromqlReducer.LastNotNull }]); expect(queriedConfig.granularity).toBe('1 minute'); }); @@ -346,27 +370,30 @@ describe('DBPieChart', () => { ); const [first, second] = mockUseQueriedChartConfig.mock.calls.map( - ([, options]) => options.queryKey, + ([, options]) => options?.queryKey, ); + expect(first).toBeDefined(); expect(second).toEqual(first); }); const mockThreeSeries = () => - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [ - { series_name: 'cart', value: 2 }, - { series_name: 'checkout', value: 7 }, - { series_name: 'ad', value: 4 }, - ], - meta: [ - { name: 'series_name', type: 'String' }, - { name: 'value', type: 'Float64' }, - ], - }, - isLoading: false, - isError: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [ + { series_name: 'cart', value: 2 }, + { series_name: 'checkout', value: 7 }, + { series_name: 'ad', value: 4 }, + ], + meta: [ + { name: 'series_name', type: 'String' }, + { name: 'value', type: 'Float64' }, + ], + }, + isLoading: false, + isError: false, + }), + ); const legendLabels = () => within(screen.getByTestId('pie-chart-legend')) diff --git a/packages/app/src/components/__tests__/DBRowDataPanel.test.ts b/packages/app/src/components/__tests__/DBRowDataPanel.test.ts index 97aa4ee114..fc21028fd2 100644 --- a/packages/app/src/components/__tests__/DBRowDataPanel.test.ts +++ b/packages/app/src/components/__tests__/DBRowDataPanel.test.ts @@ -1,6 +1,11 @@ import { ClickHouseQueryError } from '@hyperdx/common-utils/dist/clickhouse'; +import { + isPromqlChartConfig, + isRawSqlChartConfig, +} from '@hyperdx/common-utils/dist/guards'; import { SourceKind, TLogSource } from '@hyperdx/common-utils/dist/types'; import { renderHook } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import { getJSONColumnNames, @@ -26,7 +31,28 @@ jest.mock('@/hooks/useMetadata', () => ({ mockUseColumns(table, options), })); -const mockUseQueriedChartConfig = useQueriedChartConfig as jest.Mock; +const mockUseQueriedChartConfig = jest.mocked(useQueriedChartConfig); +type QueryResult = ReturnType; + +// useRowData always builds builder configs; narrowing gives access to `select`. +// Excluding the other variants (rather than isBuilderChartConfig) keeps the +// optional dateRange/timestampValueExpression of the queried config type. +function queriedConfig(call = 0) { + const [config] = mockUseQueriedChartConfig.mock.calls[call]; + if (isRawSqlChartConfig(config) || isPromqlChartConfig(config)) { + throw new Error('expected a builder chart config'); + } + return config; +} + +function queriedOptions(call = 0) { + const [, options] = mockUseQueriedChartConfig.mock.calls[call]; + if (options == null) { + throw new Error('expected query options'); + } + return options; +} + const showMaterializedAliasColumns = () => localStorage.setItem('hdx-row-show-materialized-alias-columns', 'true'); @@ -46,17 +72,19 @@ describe('DBRowDataPanel', () => { jest.clearAllMocks(); localStorage.clear(); mockColumns = { data: undefined, isLoading: false }; - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [], - meta: [], - rows: 0, - isComplete: true, - }, - isLoading: false, - isError: false, - isSuccess: true, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [], + meta: [], + rows: 0, + isComplete: true, + }, + isLoading: false, + isError: false, + isSuccess: true, + }), + ); }); describe('getJSONColumnNames', () => { @@ -90,29 +118,31 @@ describe('DBRowDataPanel', () => { it('selects `*` when the source has no Known Columns List', () => { renderHook(() => useRowData({ source, rowId: "id='abc123'" })); - const [config] = mockUseQueriedChartConfig.mock.calls[0]; + const config = queriedConfig(); expect(config.select[0]).toEqual({ valueExpression: '*' }); }); // JSON-typed Events.Attributes come back nested. it('flattens span-event exception attributes', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [ - { - __hdx_events_exception_attributes: { - exception: { type: 'TypeError' }, + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [ + { + __hdx_events_exception_attributes: { + exception: { type: 'TypeError' }, + }, }, - }, - ], - meta: [], - rows: 1, - isComplete: true, - }, - isLoading: false, - isError: false, - isSuccess: true, - }); + ], + meta: [], + rows: 1, + isComplete: true, + }, + isLoading: false, + isError: false, + isSuccess: true, + }), + ); const { result } = renderHook(() => useRowData({ source, rowId: "id='abc123'" }), @@ -133,7 +163,7 @@ describe('DBRowDataPanel', () => { useRowData({ source: sourceWithKnownColumns, rowId: "id='abc123'" }), ); - const [config] = mockUseQueriedChartConfig.mock.calls[0]; + const config = queriedConfig(); expect(config.select[0]).toEqual({ valueExpression: 'Timestamp, Body, ServiceName', }); @@ -152,16 +182,19 @@ describe('DBRowDataPanel', () => { overrides: Partial, row: Record = {}, ) => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { data: [row], meta: [], rows: 1, isComplete: true }, - isLoading: false, - isError: false, - isSuccess: true, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { data: [row], meta: [], rows: 1, isComplete: true }, + isLoading: false, + isError: false, + isSuccess: true, + }), + ); const { result } = renderHook(() => useRowData({ source: { ...source, ...overrides }, rowId: "id='a'" }), ); - const [[{ select }, { queryKey }]] = mockUseQueriedChartConfig.mock.calls; + const { select } = queriedConfig(); + const { queryKey } = queriedOptions(); return { select, queryKey, @@ -240,7 +273,7 @@ describe('DBRowDataPanel', () => { }), ); for (const [, options] of mockUseQueriedChartConfig.mock.calls) { - expect(options.enabled).toBe(false); + expect(options?.enabled).toBe(false); } expect(result.current.isLoading).toBe(true); }, @@ -291,8 +324,7 @@ describe('DBRowDataPanel', () => { it('adds no query settings while the viewer option is off', () => { renderHook(() => useRowData({ source, rowId: "id='abc123'" })); - const [bounded, fallback] = mockUseQueriedChartConfig.mock.calls; - for (const [, options] of [bounded, fallback]) { + for (const options of [queriedOptions(0), queriedOptions(1)]) { expect(options.additionalQuerySettings).toBeUndefined(); expect(options.retry).toBeUndefined(); } @@ -302,8 +334,7 @@ describe('DBRowDataPanel', () => { showMaterializedAliasColumns(); renderHook(() => useRowData({ source, rowId: "id='abc123'" })); - const [bounded, fallback] = mockUseQueriedChartConfig.mock.calls; - for (const [, options] of [bounded, fallback]) { + for (const options of [queriedOptions(0), queriedOptions(1)]) { expect(options.additionalQuerySettings).toEqual([ { setting: 'asterisk_include_materialized_columns', value: '1' }, { setting: 'asterisk_include_alias_columns', value: '1' }, @@ -324,7 +355,7 @@ describe('DBRowDataPanel', () => { useRowData({ source: sourceWithSetting, rowId: "id='abc123'" }), ); - const [[, options]] = mockUseQueriedChartConfig.mock.calls; + const options = queriedOptions(); expect(options.additionalQuerySettings).toEqual([ { setting: 'asterisk_include_materialized_columns', value: '1' }, ]); @@ -344,7 +375,7 @@ describe('DBRowDataPanel', () => { useRowData({ source: sourceWithSettings, rowId: "id='abc123'" }), ); - const [[, options]] = mockUseQueriedChartConfig.mock.calls; + const options = queriedOptions(); expect(options.additionalQuerySettings).toBeUndefined(); }); @@ -359,8 +390,7 @@ describe('DBRowDataPanel', () => { useRowData({ source: sourceWithKnownColumns, rowId: "id='abc123'" }), ); - const [bounded, fallback] = mockUseQueriedChartConfig.mock.calls; - for (const [, options] of [bounded, fallback]) { + for (const options of [queriedOptions(0), queriedOptions(1)]) { expect(options.additionalQuerySettings).toBeUndefined(); } }); @@ -375,14 +405,16 @@ describe('DBRowDataPanel', () => { code: '164', type: 'READONLY', }); - mockUseQueriedChartConfig.mockReturnValue({ - data: undefined, - error: readonlyError, - isLoading: false, - isPending: false, - isError: true, - isSuccess: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: undefined, + error: readonlyError, + isLoading: false, + isPending: false, + isError: true, + isSuccess: false, + }), + ); const { result } = renderHook(() => useRowData({ source, rowId: "id='abc123'" }), @@ -392,7 +424,7 @@ describe('DBRowDataPanel', () => { expect(result.current.error).toBe(readonlyError); expect(result.current.isLoading).toBe(false); for (const [, options] of mockUseQueriedChartConfig.mock.calls) { - expect(options.additionalQuerySettings).toBeDefined(); + expect(options?.additionalQuerySettings).toBeDefined(); } }); @@ -403,7 +435,7 @@ describe('DBRowDataPanel', () => { it('omits the time filter when no dateRange is given', () => { renderHook(() => useRowData({ source, rowId: "id='abc123'" })); - const [config] = mockUseQueriedChartConfig.mock.calls[0]; + const config = queriedConfig(); expect(config.dateRange).toBeUndefined(); expect(config.timestampValueExpression).toBeUndefined(); }); @@ -416,7 +448,8 @@ describe('DBRowDataPanel', () => { renderHook(() => useRowData({ source, rowId: "id='abc123'", dateRange })); - const [config, options] = mockUseQueriedChartConfig.mock.calls[0]; + const config = queriedConfig(); + const options = queriedOptions(); expect(config.dateRange).toBe(dateRange); expect(config.timestampValueExpression).toBe('Timestamp'); // Filtered and unfiltered lookups for the same row must not share a @@ -444,7 +477,7 @@ describe('DBRowDataPanel', () => { }), ); - const [config] = mockUseQueriedChartConfig.mock.calls[0]; + const config = queriedConfig(); expect(config.timestampValueExpression).toBe('EventDate, EventTime'); }); @@ -467,7 +500,7 @@ describe('DBRowDataPanel', () => { }), ); - const [config] = mockUseQueriedChartConfig.mock.calls[0]; + const config = queriedConfig(); expect(config.dateRange).toBeUndefined(); expect(config.timestampValueExpression).toBeUndefined(); }); @@ -484,8 +517,8 @@ describe('DBRowDataPanel', () => { }), ); - const [, boundedOptions] = mockUseQueriedChartConfig.mock.calls[0]; - const [, fallbackOptions] = mockUseQueriedChartConfig.mock.calls[1]; + const boundedOptions = queriedOptions(0); + const fallbackOptions = queriedOptions(1); expect(boundedOptions.queryKey).not.toEqual(fallbackOptions.queryKey); }); }); @@ -502,15 +535,19 @@ describe('DBRowDataPanel', () => { ]; const ROW = { __hdx_timestamp: '2024-01-01T01:00:00Z' }; - function lookupResult(overrides: Record = {}) { - return { - data: { data: [], meta: [], rows: 0, isComplete: true }, + function lookupResult( + data: { + data: Record[]; + isComplete: boolean; + } = { data: [], isComplete: true }, + ): QueryResult { + return fromPartial({ + data: { meta: [], rows: data.data.length, ...data }, isLoading: false, isPending: false, isError: false, isSuccess: true, - ...overrides, - }; + }); } // Dispatch on the query key rather than a call counter, so the mock is @@ -520,14 +557,16 @@ describe('DBRowDataPanel', () => { bounded, fallback, }: { - bounded: ReturnType; - fallback: ReturnType; + bounded: QueryResult; + fallback: QueryResult; }) { - mockUseQueriedChartConfig.mockImplementation((_config, options) => - options.queryKey[options.queryKey.length - 1] === undefined - ? fallback - : bounded, - ); + mockUseQueriedChartConfig.mockImplementation((_config, options) => { + const queryKey = options?.queryKey; + if (queryKey == null) { + throw new Error('expected a query key'); + } + return queryKey[queryKey.length - 1] === undefined ? fallback : bounded; + }); } function renderLookup(dateRange?: [Date, Date]) { @@ -537,8 +576,8 @@ describe('DBRowDataPanel', () => { } function enabledFlags() { - const [, boundedOptions] = mockUseQueriedChartConfig.mock.calls[0]; - const [, fallbackOptions] = mockUseQueriedChartConfig.mock.calls[1]; + const boundedOptions = queriedOptions(0); + const fallbackOptions = queriedOptions(1); return { bounded: boundedOptions.enabled, fallback: fallbackOptions.enabled, @@ -547,9 +586,7 @@ describe('DBRowDataPanel', () => { it('does not run when the bounded lookup finds the row', () => { mockLookups({ - bounded: lookupResult({ - data: { data: [ROW], meta: [], rows: 1, isComplete: true }, - }), + bounded: lookupResult({ data: [ROW], isComplete: true }), fallback: lookupResult(), }); @@ -570,9 +607,7 @@ describe('DBRowDataPanel', () => { it('serves the row the bounded lookup missed', () => { mockLookups({ bounded: lookupResult(), - fallback: lookupResult({ - data: { data: [ROW], meta: [], rows: 1, isComplete: true }, - }), + fallback: lookupResult({ data: [ROW], isComplete: true }), }); const { result } = renderLookup(DATE_RANGE); @@ -585,8 +620,10 @@ describe('DBRowDataPanel', () => { it('does not run when the bounded lookup errors', () => { const error = new Error('boom'); mockLookups({ - bounded: lookupResult({ + bounded: fromPartial({ data: undefined, + isLoading: false, + isPending: false, isSuccess: false, isError: true, error, @@ -614,8 +651,9 @@ describe('DBRowDataPanel', () => { it('reports loading while in flight', () => { mockLookups({ bounded: lookupResult(), - fallback: lookupResult({ + fallback: fromPartial({ data: undefined, + isError: false, isSuccess: false, isLoading: false, isPending: true, @@ -631,9 +669,7 @@ describe('DBRowDataPanel', () => { // first chunk must not read as "no such row". it('does not run on an incomplete bounded result', () => { mockLookups({ - bounded: lookupResult({ - data: { data: [], meta: [], rows: 0, isComplete: false }, - }), + bounded: lookupResult({ data: [], isComplete: false }), fallback: lookupResult(), }); @@ -644,9 +680,10 @@ describe('DBRowDataPanel', () => { }); describe('__hdx_timestamp_value_', () => { - function timestampValueSelects(config: { - select: { alias?: string }[]; - }): { alias?: string }[] { + function timestampValueSelects(config: ReturnType) { + if (typeof config.select === 'string') { + throw new Error('expected a select list'); + } return config.select.filter(s => s.alias?.startsWith('__hdx_timestamp_value_'), ); @@ -665,7 +702,7 @@ describe('DBRowDataPanel', () => { }), ); - const [config] = mockUseQueriedChartConfig.mock.calls[0]; + const config = queriedConfig(); expect(config.select).toContainEqual({ valueExpression: 'ObservedTimestamp', alias: '__hdx_timestamp', @@ -688,7 +725,7 @@ describe('DBRowDataPanel', () => { useRowData({ source: multiColumnSource, rowId: "id='abc123'" }), ); - const [config] = mockUseQueriedChartConfig.mock.calls[0]; + const config = queriedConfig(); expect(timestampValueSelects(config)).toEqual([ { valueExpression: 'EventDate', alias: '__hdx_timestamp_value_0' }, { valueExpression: 'EventTime', alias: '__hdx_timestamp_value_1' }, @@ -705,7 +742,7 @@ describe('DBRowDataPanel', () => { useRowData({ source: sourceWithoutTimestamp, rowId: "id='abc123'" }), ); - const [config] = mockUseQueriedChartConfig.mock.calls[0]; + const config = queriedConfig(); expect(timestampValueSelects(config)).toEqual([]); }); }); diff --git a/packages/app/src/components/__tests__/DBTimeChart.test.tsx b/packages/app/src/components/__tests__/DBTimeChart.test.tsx index 66e977c30c..6a1eac12ed 100644 --- a/packages/app/src/components/__tests__/DBTimeChart.test.tsx +++ b/packages/app/src/components/__tests__/DBTimeChart.test.tsx @@ -61,9 +61,9 @@ jest.mock('../MaterializedViews/MVOptimizationIndicator', () => jest.mock('../charts/DateRangeIndicator', () => jest.fn(() => null)); describe('DBTimeChart', () => { - const mockUseQueriedChartConfig = useQueriedChartConfig as jest.Mock; - const mockUseMe = api.useMe as jest.Mock; - const mockUseSource = useSource as jest.Mock; + const mockUseQueriedChartConfig = jest.mocked(useQueriedChartConfig); + const mockUseMe = jest.mocked(api.useMe); + const mockUseSource = jest.mocked(useSource); const baseTestConfig = { dateRange: [new Date('2024-01-01'), new Date('2024-01-02')] as [Date, Date], @@ -77,28 +77,34 @@ describe('DBTimeChart', () => { beforeEach(() => { jest.clearAllMocks(); - mockUseMe.mockReturnValue({ - data: { team: { parallelizeWhenPossible: false } }, - isLoading: false, - }); + mockUseMe.mockReturnValue( + fromPartial({ + data: { team: { parallelizeWhenPossible: false } }, + isLoading: false, + }), + ); - mockUseSource.mockReturnValue({ - data: undefined, - isLoading: false, - }); + mockUseSource.mockReturnValue( + fromPartial({ + data: undefined, + isLoading: false, + }), + ); - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [{ timestamp: 1704067200, value: 100 }], - meta: [], - rows: 1, - isComplete: true, - }, - isLoading: false, - isError: false, - isSuccess: true, - isPlaceholderData: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [{ timestamp: 1704067200, value: 100 }], + meta: [], + rows: 1, + isComplete: true, + }, + isLoading: false, + isError: false, + isSuccess: true, + isPlaceholderData: false, + }), + ); }); it('passes enabled: false to useQueriedChartConfig for previous period when compareToPreviousPeriod is undefined', () => { @@ -113,7 +119,7 @@ describe('DBTimeChart', () => { const [, secondCallOptions] = mockUseQueriedChartConfig.mock.calls[1]; // Verify that enabled is false for the previous period query - expect(secondCallOptions.enabled).toBe(false); + expect(secondCallOptions?.enabled).toBe(false); }); it('passes enabled: true to useQueriedChartConfig for previous period when compareToPreviousPeriod is true', () => { @@ -128,7 +134,7 @@ describe('DBTimeChart', () => { const [, secondCallOptions] = mockUseQueriedChartConfig.mock.calls[1]; // Verify that enabled is true for the previous period query - expect(secondCallOptions.enabled).toBe(true); + expect(secondCallOptions?.enabled).toBe(true); }); it('passes enabled: false to useQueriedChartConfig for previous period when compareToPreviousPeriod is false', () => { @@ -143,7 +149,7 @@ describe('DBTimeChart', () => { const [, secondCallOptions] = mockUseQueriedChartConfig.mock.calls[1]; // Verify that enabled is false for the previous period query - expect(secondCallOptions.enabled).toBe(false); + expect(secondCallOptions?.enabled).toBe(false); }); it('respects the enabled prop when determining if previous period query should run', () => { @@ -160,37 +166,38 @@ describe('DBTimeChart', () => { // Verify that enabled is false even when compareToPreviousPeriod is true // because the enabled prop is false - expect(secondCallOptions.enabled).toBe(false); + expect(secondCallOptions?.enabled).toBe(false); }); describe('empty state', () => { - const emptyResult = { - data: { - data: [], - meta: [ - { name: 'timestamp', type: 'DateTime' }, - { name: 'value', type: 'UInt64' }, - ], - rows: 0, - isComplete: true, - }, - isLoading: false, - isFetching: false, - isError: false, - isSuccess: true, - isPlaceholderData: false, - }; + const emptyResult = ({ isFetching = false } = {}) => + fromPartial>({ + data: { + data: [], + meta: [ + { name: 'timestamp', type: 'DateTime' }, + { name: 'value', type: 'UInt64' }, + ], + rows: 0, + isComplete: !isFetching, + }, + isLoading: false, + isFetching, + isError: false, + isSuccess: true, + isPlaceholderData: false, + }); // Zero-filled buckets would otherwise render an empty line, not the empty state. const emptyConfig = { ...baseTestConfig, fillNulls: false as const }; - const isPreviousPeriod = (config: { dateRange: [Date, Date] }) => - config.dateRange[0] < baseTestConfig.dateRange[0]; + const isPreviousPeriod = (config: { dateRange?: [Date, Date] }) => { + const start = config.dateRange?.[0]; + return start != null && start < baseTestConfig.dateRange[0]; + }; it('shows loading while the query is still fetching', () => { - mockUseQueriedChartConfig.mockReturnValue({ - ...emptyResult, - data: { ...emptyResult.data, isComplete: false }, - isFetching: true, - }); + mockUseQueriedChartConfig.mockReturnValue( + emptyResult({ isFetching: true }), + ); renderWithMantine(); @@ -200,7 +207,7 @@ describe('DBTimeChart', () => { it('shows no data when the previous-period query fails', () => { mockUseQueriedChartConfig.mockImplementation(config => isPreviousPeriod(config) - ? { + ? fromPartial({ data: undefined, isLoading: false, isFetching: false, @@ -208,8 +215,8 @@ describe('DBTimeChart', () => { error: new Error('previous period failed'), isSuccess: false, isPlaceholderData: false, - } - : emptyResult, + }) + : emptyResult(), ); renderWithMantine( @@ -342,18 +349,20 @@ describe('DBTimeChart', () => { }; beforeEach(() => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: highCardinalityData, - meta: highCardinalityMeta, - rows: GROUP_COUNT, - isComplete: true, - }, - isLoading: false, - isError: false, - isSuccess: true, - isPlaceholderData: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: highCardinalityData, + meta: highCardinalityMeta, + rows: GROUP_COUNT, + isComplete: true, + }, + isLoading: false, + isError: false, + isSuccess: true, + isPlaceholderData: false, + }), + ); }); it('surfaces the load-all button when the render cap hides series, then hides it after loading all', async () => { @@ -480,18 +489,20 @@ describe('DBTimeChart', () => { value: i + 1, group: `g${i}`, })); - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: bigData, - meta: highCardinalityMeta, - rows: BIG_GROUP_COUNT, - isComplete: true, - }, - isLoading: false, - isError: false, - isSuccess: true, - isPlaceholderData: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: bigData, + meta: highCardinalityMeta, + rows: BIG_GROUP_COUNT, + isComplete: true, + }, + isLoading: false, + isError: false, + isSuccess: true, + isPlaceholderData: false, + }), + ); renderWithMantine(); @@ -664,8 +675,10 @@ describe('DBTimeChart', () => { const firstCallConfig = mockUseQueriedChartConfig.mock.calls[0][0]; // The config should be passed as-is, not wrapped by convertToTimeChartConfig // (which would add `limit`, `dateRangeEndInclusive`, etc.) - expect(firstCallConfig.configType).toBe('sql'); - expect(firstCallConfig.sqlTemplate).toBe(rawSqlConfig.sqlTemplate); + expect(firstCallConfig).toMatchObject({ + configType: 'sql', + sqlTemplate: rawSqlConfig.sqlTemplate, + }); expect(firstCallConfig).not.toHaveProperty('limit'); }); @@ -679,24 +692,26 @@ describe('DBTimeChart', () => { }); it('renders without crashing when query returns timestamp and value columns', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [ - { ts: 1704067200, count: 42 }, - { ts: 1704067260, count: 17 }, - ], - meta: [ - { name: 'ts', type: 'DateTime' }, - { name: 'count', type: 'UInt64' }, - ], - rows: 2, - isComplete: true, - }, - isLoading: false, - isError: false, - isSuccess: true, - isPlaceholderData: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [ + { ts: 1704067200, count: 42 }, + { ts: 1704067260, count: 17 }, + ], + meta: [ + { name: 'ts', type: 'DateTime' }, + { name: 'count', type: 'UInt64' }, + ], + rows: 2, + isComplete: true, + }, + isLoading: false, + isError: false, + isSuccess: true, + isPlaceholderData: false, + }), + ); // Should render without throwing expect(() => @@ -705,18 +720,20 @@ describe('DBTimeChart', () => { }); it('renders without crashing when query returns no data', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [], - meta: [], - rows: 0, - isComplete: true, - }, - isLoading: false, - isError: false, - isSuccess: true, - isPlaceholderData: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [], + meta: [], + rows: 0, + isComplete: true, + }, + isLoading: false, + isError: false, + isSuccess: true, + isPlaceholderData: false, + }), + ); expect(() => renderWithMantine(), @@ -724,25 +741,27 @@ describe('DBTimeChart', () => { }); it('renders without crashing when query returns multiple value columns', () => { - mockUseQueriedChartConfig.mockReturnValue({ - data: { - data: [ - { ts: 1704067200, errors: 5, warnings: 12 }, - { ts: 1704067260, errors: 3, warnings: 8 }, - ], - meta: [ - { name: 'ts', type: 'DateTime' }, - { name: 'errors', type: 'UInt64' }, - { name: 'warnings', type: 'UInt64' }, - ], - rows: 2, - isComplete: true, - }, - isLoading: false, - isError: false, - isSuccess: true, - isPlaceholderData: false, - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: { + data: [ + { ts: 1704067200, errors: 5, warnings: 12 }, + { ts: 1704067260, errors: 3, warnings: 8 }, + ], + meta: [ + { name: 'ts', type: 'DateTime' }, + { name: 'errors', type: 'UInt64' }, + { name: 'warnings', type: 'UInt64' }, + ], + rows: 2, + isComplete: true, + }, + isLoading: false, + isError: false, + isSuccess: true, + isPlaceholderData: false, + }), + ); expect(() => renderWithMantine(), diff --git a/packages/app/src/components/__tests__/DBTraceWaterfallChart.test.tsx b/packages/app/src/components/__tests__/DBTraceWaterfallChart.test.tsx index 693b61f0e1..4400f10249 100644 --- a/packages/app/src/components/__tests__/DBTraceWaterfallChart.test.tsx +++ b/packages/app/src/components/__tests__/DBTraceWaterfallChart.test.tsx @@ -1,5 +1,8 @@ import React from 'react'; +import { ColumnMeta } from '@hyperdx/common-utils/dist/clickhouse'; +import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards'; import { + ChartConfigWithOptTimestamp, SourceKind, TLogSource, TTraceSource, @@ -7,6 +10,7 @@ import { import { screen, waitFor } from '@testing-library/react'; import { renderHook } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { fromPartial } from '@total-typescript/shoehorn'; import { RowSidePanelContext } from '@/components/DBRowSidePanel'; import { @@ -131,18 +135,31 @@ jest.mock('@/hooks/useWaterfallSearchState', () => ({ default: (...args: any[]) => mockUseWaterfallSearchState(...args), })); -const mockUseOffsetPaginatedQuery = useOffsetPaginatedQuery as jest.Mock; -const mockUseRowWhere = useRowWhere as jest.Mock; -const mockUseColumns = useColumns as jest.Mock; +const mockUseOffsetPaginatedQuery = jest.mocked(useOffsetPaginatedQuery); +const mockUseRowWhere = jest.mocked(useRowWhere); +const mockUseColumns = jest.mocked(useColumns); const MockTimelineChart = TimelineChart as any; // Mirrors useColumns, which is disabled, so never loading, without a table. -const setupColumnsMock = (state: { data?: object[]; isLoading?: boolean }) => - mockUseColumns.mockImplementation(({ tableName }: { tableName: string }) => - tableName ? { isLoading: false, ...state } : { isLoading: false }, +// A loading query result carries no data, so the two states are built apart. +const setupColumnsMock = ({ + data, + isLoading = false, +}: { + data?: Partial[]; + isLoading?: boolean; +}) => + mockUseColumns.mockImplementation(({ tableName }) => + fromPartial( + tableName && isLoading + ? { isLoading: true } + : { isLoading: false, data: tableName ? data : undefined }, + ), ); -const selectsSeverityNumber = (query: { select: Array<{ alias?: string }> }) => +const selectsSeverityNumber = (query: ChartConfigWithOptTimestamp) => + isBuilderChartConfig(query) && + Array.isArray(query.select) && query.select.some(s => s.alias === 'SeverityNumber'); describe('DBTraceWaterfallChartContainer', () => { @@ -294,7 +311,11 @@ describe('DBTraceWaterfallChartContainer', () => { mockUseOffsetPaginatedQuery.mockImplementation((query: any, opts: any) => { // Disabled queries never fire (mirrors react-query). if (opts?.enabled === false) { - return { data: undefined, isFetching: false, error: undefined }; + return fromPartial({ + data: undefined, + isFetching: false, + error: undefined, + }); } const isLog = query?.from?.tableName === 'log_table'; const isBefore = query?.dateRangeStartInclusive === true; @@ -304,28 +325,30 @@ describe('DBTraceWaterfallChartContainer', () => { const fatal = isLog ? logError : traceError; if (fatal) { - return { data: undefined, isFetching, error: fatal }; + return fromPartial({ data: undefined, isFetching, error: fatal }); } const filterErr = isLog ? logFilterError : traceFilterError; if (filterErr && isFiltered) { - return { data: undefined, isFetching, error: filterErr }; + return fromPartial({ data: undefined, isFetching, error: filterErr }); } const data = isLog ? logData : traceData; - return { + return fromPartial({ data: isBefore ? data : emptyData, isFetching, error: undefined, - }; + }); }); }; // Test cases it('renders loading state when data is being fetched', () => { - mockUseOffsetPaginatedQuery.mockReturnValue({ - data: undefined, - isFetching: true, - }); + mockUseOffsetPaginatedQuery.mockReturnValue( + fromPartial({ + data: undefined, + isFetching: true, + }), + ); renderComponent(); expect(screen.getByText('Loading Traces...')).toBeInTheDocument(); }); @@ -726,10 +749,12 @@ describe('DBTraceWaterfallChartContainer', () => { ); }); it('renders empty state when no data is available', async () => { - mockUseOffsetPaginatedQuery.mockReturnValue({ - data: emptyData, - isFetching: false, - }); + mockUseOffsetPaginatedQuery.mockReturnValue( + fromPartial({ + data: emptyData, + isFetching: false, + }), + ); renderComponent(); @@ -746,9 +771,9 @@ describe('DBTraceWaterfallChartContainer', () => { renderComponent(mockLogTableSource, "trace'with-quote"); expect(mockUseOffsetPaginatedQuery).toHaveBeenCalled(); - expect(mockUseOffsetPaginatedQuery.mock.calls[0][0].where).toBe( - "TraceId = 'trace\\'with-quote'", - ); + expect(mockUseOffsetPaginatedQuery.mock.calls[0]?.[0]).toMatchObject({ + where: "TraceId = 'trace\\'with-quote'", + }); }); it('renders HTTP spans with URL information', async () => { @@ -1436,13 +1461,19 @@ describe('useEventsAroundFocus', () => { if (enabled) { mockUseOffsetPaginatedQuery - .mockReturnValueOnce({ data: beforeData, isFetching: false }) - .mockReturnValueOnce({ data: afterData, isFetching: false }); + .mockReturnValueOnce( + fromPartial({ data: beforeData, isFetching: false }), + ) + .mockReturnValueOnce( + fromPartial({ data: afterData, isFetching: false }), + ); } else { - mockUseOffsetPaginatedQuery.mockReturnValue({ - data: { data: [], meta: [] }, - isFetching: false, - }); + mockUseOffsetPaginatedQuery.mockReturnValue( + fromPartial({ + data: { data: [], meta: [] }, + isFetching: false, + }), + ); } const { result } = renderHook(() => diff --git a/packages/app/src/components/__tests__/NumberTileBackgroundChart.test.tsx b/packages/app/src/components/__tests__/NumberTileBackgroundChart.test.tsx index 835cae7857..1c9ac9c7e1 100644 --- a/packages/app/src/components/__tests__/NumberTileBackgroundChart.test.tsx +++ b/packages/app/src/components/__tests__/NumberTileBackgroundChart.test.tsx @@ -1,6 +1,8 @@ import React from 'react'; +import { isPromqlChartConfig } from '@hyperdx/common-utils/dist/guards'; import { DisplayType, PromqlReducer } from '@hyperdx/common-utils/dist/types'; import { screen } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import { convertToPromqlSparklineChartConfig } from '@/ChartUtils'; import NumberTileBackgroundChart, { @@ -150,12 +152,12 @@ describe('buildSparklineQueryConfig', () => { }); describe('NumberTileBackgroundChart', () => { - const mockUseQueriedChartConfig = useQueriedChartConfig as jest.Mock; + const mockUseQueriedChartConfig = jest.mocked(useQueriedChartConfig); beforeEach(() => { jest.clearAllMocks(); - mockUseQueriedChartConfig.mockReturnValue({ data: undefined }); - (useSource as jest.Mock).mockReturnValue({ data: null }); + mockUseQueriedChartConfig.mockReturnValue(fromPartial({ data: undefined })); + jest.mocked(useSource).mockReturnValue(fromPartial({ data: undefined })); }); it('strips groupBy from the issued query so the sparkline matches the single displayed aggregate', () => { @@ -185,7 +187,10 @@ describe('NumberTileBackgroundChart', () => { expect(queriedConfig).not.toHaveProperty('groupBy'); // A builder tile has no query to share with its value, so it keeps its own // namespaced key rather than the one the hook builds. - expect(options.queryKey).toEqual(['number-tile-background', queriedConfig]); + expect(options?.queryKey).toEqual([ + 'number-tile-background', + queriedConfig, + ]); }); it('issues no query while the tile is disabled', () => { @@ -208,7 +213,7 @@ describe('NumberTileBackgroundChart', () => { ); const [, options] = mockUseQueriedChartConfig.mock.calls[0]; - expect(options.enabled).toBe(false); + expect(options?.enabled).toBe(false); }); it("scopes a builder tile's own key with the prefix, when given one", () => { @@ -231,7 +236,7 @@ describe('NumberTileBackgroundChart', () => { ); const [queriedConfig, options] = mockUseQueriedChartConfig.mock.calls[0]; - expect(options.queryKey).toEqual([ + expect(options?.queryKey).toEqual([ 'tile-1', 'number-tile-background', queriedConfig, @@ -328,9 +333,11 @@ describe('NumberTileBackgroundChart', () => { it('plots one point per sample, with no zeros between them', () => { const values = [1, 1.2, 1.1, 1.3, 1.25, 1.4, 1.35, 1.5, 1.45, 1.6, 1.55]; - mockUseQueriedChartConfig.mockReturnValue({ - data: sampleRows(values, promqlConfig.dateRange[0], 60), - }); + mockUseQueriedChartConfig.mockReturnValue( + fromPartial({ + data: sampleRows(values, promqlConfig.dateRange[0], 60), + }), + ); renderWithMantine( { ); const queriedConfig = mockUseQueriedChartConfig.mock.calls[0][0]; - expect(queriedConfig.promqlExpression).toEqual([ - { expression: 'e2e_service_up', queryType: 'range' }, - ]); + expect( + isPromqlChartConfig(queriedConfig) && queriedConfig.promqlExpression, + ).toEqual([{ expression: 'e2e_service_up', queryType: 'range' }]); }); // An instant query answers with a single point, so there is no trend. diff --git a/packages/app/src/components/__tests__/SourceSelect.test.tsx b/packages/app/src/components/__tests__/SourceSelect.test.tsx index 1e881878ad..dcc733df7c 100644 --- a/packages/app/src/components/__tests__/SourceSelect.test.tsx +++ b/packages/app/src/components/__tests__/SourceSelect.test.tsx @@ -7,6 +7,7 @@ import { } from '@hyperdx/common-utils/dist/types'; import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { fromPartial } from '@total-typescript/shoehorn'; import { SourceManagementMenu, @@ -22,9 +23,6 @@ jest.mock('@/source', () => ({ // Mantine's Combobox calls scrollIntoView when its dropdown opens; jsdom lacks it. window.HTMLElement.prototype.scrollIntoView = jest.fn(); -// useSources returns a large UseQueryResult; the selector reads only `data`. -const asMock = (fn: unknown) => fn as jest.Mock; - const makeSource = ( id: string, name: string, @@ -213,7 +211,9 @@ describe('SourceSelectControlled (grouped rendering + tag-style search)', () => }; it('renders sources grouped under their section headers', async () => { - asMock(useSources).mockReturnValue({ data: SECTIONED_SOURCES }); + jest + .mocked(useSources) + .mockReturnValue(fromPartial({ data: SECTIONED_SOURCES })); renderWithMantine(); await openSelect(); @@ -227,7 +227,9 @@ describe('SourceSelectControlled (grouped rendering + tag-style search)', () => }); it('treats the section as a tag: "billing logs" keeps section-mates whose name lacks "billing" and drops other sections', async () => { - asMock(useSources).mockReturnValue({ data: SECTIONED_SOURCES }); + jest + .mocked(useSources) + .mockReturnValue(fromPartial({ data: SECTIONED_SOURCES })); renderWithMantine(); const input = await openSelect(); await userEvent.type(input, 'billing logs'); @@ -243,7 +245,9 @@ describe('SourceSelectControlled (grouped rendering + tag-style search)', () => }); it('selects the current label on a focusing click so typing replaces it', async () => { - asMock(useSources).mockReturnValue({ data: SECTIONED_SOURCES }); + jest + .mocked(useSources) + .mockReturnValue(fromPartial({ data: SECTIONED_SOURCES })); renderWithMantine(); const input = screen.getByPlaceholderText('Data Source'); expect(input).toHaveValue('Billing Logs'); @@ -259,7 +263,9 @@ describe('SourceSelectControlled (grouped rendering + tag-style search)', () => }); it('places the caret normally on a click into an already focused input', async () => { - asMock(useSources).mockReturnValue({ data: SECTIONED_SOURCES }); + jest + .mocked(useSources) + .mockReturnValue(fromPartial({ data: SECTIONED_SOURCES })); renderWithMantine(); const input = screen.getByPlaceholderText('Data Source'); @@ -269,7 +275,9 @@ describe('SourceSelectControlled (grouped rendering + tag-style search)', () => }); it('hides sources rejected by isSourceAllowed, along with sections left empty', async () => { - asMock(useSources).mockReturnValue({ data: SECTIONED_SOURCES }); + jest + .mocked(useSources) + .mockReturnValue(fromPartial({ data: SECTIONED_SOURCES })); renderWithMantine( source.section === 'Billing'} @@ -284,12 +292,14 @@ describe('SourceSelectControlled (grouped rendering + tag-style search)', () => }); it('stays flat with no catch-all header until a source has a section', async () => { - asMock(useSources).mockReturnValue({ - data: [ - makeSource('a', 'Apple Traces', SourceKind.Trace), - makeSource('z', 'Zebra Logs', SourceKind.Log), - ], - }); + jest.mocked(useSources).mockReturnValue( + fromPartial({ + data: [ + makeSource('a', 'Apple Traces', SourceKind.Trace), + makeSource('z', 'Zebra Logs', SourceKind.Log), + ], + }), + ); renderWithMantine(); await openSelect(); @@ -344,7 +354,7 @@ describe('SourceSelectControlled (data source variables)', () => { } it('offers only variables with at least one kind the picker allows', async () => { - asMock(useSources).mockReturnValue({ data: SOURCES }); + jest.mocked(useSources).mockReturnValue(fromPartial({ data: SOURCES })); renderWithMantine(); await userEvent.click(screen.getByPlaceholderText('Data Source')); @@ -355,7 +365,7 @@ describe('SourceSelectControlled (data source variables)', () => { }); it('puts unsectioned sources under their own header after the variables', async () => { - asMock(useSources).mockReturnValue({ data: SOURCES }); + jest.mocked(useSources).mockReturnValue(fromPartial({ data: SOURCES })); renderWithMantine(); await userEvent.click(screen.getByPlaceholderText('Data Source')); @@ -364,7 +374,7 @@ describe('SourceSelectControlled (data source variables)', () => { }); it('offers only variables unlimited or limited to its connection', async () => { - asMock(useSources).mockReturnValue({ data: SOURCES }); + jest.mocked(useSources).mockReturnValue(fromPartial({ data: SOURCES })); function ConnectionHarness() { const { control } = useForm(); return ( @@ -394,7 +404,7 @@ describe('SourceSelectControlled (data source variables)', () => { }); it('offers no variables unless the picker opts in', async () => { - asMock(useSources).mockReturnValue({ data: SOURCES }); + jest.mocked(useSources).mockReturnValue(fromPartial({ data: SOURCES })); renderWithMantine(); await userEvent.click(screen.getByPlaceholderText('Data Source')); diff --git a/packages/app/src/components/__tests__/SourcesList.test.tsx b/packages/app/src/components/__tests__/SourcesList.test.tsx index 7685511def..50d2374b1e 100644 --- a/packages/app/src/components/__tests__/SourcesList.test.tsx +++ b/packages/app/src/components/__tests__/SourcesList.test.tsx @@ -1,5 +1,6 @@ import { SourceKind, TSource } from '@hyperdx/common-utils/dist/types'; import { screen } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import { SourcesList } from '@/components/Sources/SourcesList'; import { useConnections } from '@/connection'; @@ -15,8 +16,6 @@ jest.mock('@/config', () => ({ IS_LOCAL_MODE: false })); // does not pull in the full source form. jest.mock('../Sources/SourceForm', () => ({ TableSourceForm: () => null })); -const asMock = (fn: unknown) => fn as jest.Mock; - const makeSource = ( id: string, name: string, @@ -32,22 +31,26 @@ const makeSource = ( describe('SourcesList section display', () => { beforeEach(() => { - asMock(useConnections).mockReturnValue({ - data: [{ id: 'conn-a', name: 'Default' }], - isLoading: false, - refetch: jest.fn(), - }); + jest.mocked(useConnections).mockReturnValue( + fromPartial({ + data: [{ id: 'conn-a', name: 'Default' }], + isLoading: false, + refetch: jest.fn(), + }), + ); }); it('shows the section on a sectioned source and nothing on an unsectioned one', () => { - asMock(useSources).mockReturnValue({ - data: [ - makeSource('a', 'Billing Logs', { section: 'Billing' }), - makeSource('b', 'Plain Source'), - ], - isLoading: false, - refetch: jest.fn(), - }); + jest.mocked(useSources).mockReturnValue( + fromPartial({ + data: [ + makeSource('a', 'Billing Logs', { section: 'Billing' }), + makeSource('b', 'Plain Source'), + ], + isLoading: false, + refetch: jest.fn(), + }), + ); renderWithMantine(); expect(screen.getByText('Billing Logs')).toBeInTheDocument(); @@ -57,11 +60,13 @@ describe('SourcesList section display', () => { }); it('shows no section labels when no source has a section', () => { - asMock(useSources).mockReturnValue({ - data: [makeSource('a', 'App'), makeSource('b', 'Host')], - isLoading: false, - refetch: jest.fn(), - }); + jest.mocked(useSources).mockReturnValue( + fromPartial({ + data: [makeSource('a', 'App'), makeSource('b', 'Host')], + isLoading: false, + refetch: jest.fn(), + }), + ); renderWithMantine(); expect(screen.getByText('App')).toBeInTheDocument(); @@ -69,17 +74,19 @@ describe('SourcesList section display', () => { }); it('shows the plural kind label for each source', () => { - asMock(useSources).mockReturnValue({ - data: [ - makeSource('a', 'A'), - makeSource('b', 'B', { kind: SourceKind.Trace }), - makeSource('c', 'C', { kind: SourceKind.Metric }), - makeSource('d', 'D', { kind: SourceKind.Session }), - makeSource('e', 'E', { kind: SourceKind.Promql }), - ], - isLoading: false, - refetch: jest.fn(), - }); + jest.mocked(useSources).mockReturnValue( + fromPartial({ + data: [ + makeSource('a', 'A'), + makeSource('b', 'B', { kind: SourceKind.Trace }), + makeSource('c', 'C', { kind: SourceKind.Metric }), + makeSource('d', 'D', { kind: SourceKind.Session }), + makeSource('e', 'E', { kind: SourceKind.Promql }), + ], + isLoading: false, + refetch: jest.fn(), + }), + ); renderWithMantine(); for (const label of [ @@ -94,29 +101,33 @@ describe('SourcesList section display', () => { }); it('names a PromQL source after the connection it reads from', () => { - asMock(useConnections).mockReturnValue({ - data: [ - { id: 'conn-a', name: 'Default' }, - { id: 'conn-prom', name: 'Thanos', isPrometheusEndpoint: true }, - ], - isLoading: false, - refetch: jest.fn(), - }); - asMock(useSources).mockReturnValue({ - data: [ - makeSource('a', 'A', { kind: SourceKind.Promql }), - makeSource('b', 'B', { - kind: SourceKind.Promql, - connection: 'conn-prom', - }), - makeSource('c', 'C', { - kind: SourceKind.Promql, - connection: 'conn-missing', - }), - ], - isLoading: false, - refetch: jest.fn(), - }); + jest.mocked(useConnections).mockReturnValue( + fromPartial({ + data: [ + { id: 'conn-a', name: 'Default' }, + { id: 'conn-prom', name: 'Thanos', isPrometheusEndpoint: true }, + ], + isLoading: false, + refetch: jest.fn(), + }), + ); + jest.mocked(useSources).mockReturnValue( + fromPartial({ + data: [ + makeSource('a', 'A', { kind: SourceKind.Promql }), + makeSource('b', 'B', { + kind: SourceKind.Promql, + connection: 'conn-prom', + }), + makeSource('c', 'C', { + kind: SourceKind.Promql, + connection: 'conn-missing', + }), + ], + isLoading: false, + refetch: jest.fn(), + }), + ); renderWithMantine(); expect(screen.getByText('Time Series')).toBeInTheDocument(); diff --git a/packages/app/src/components/__tests__/sourceFormPickerDropdowns.test.tsx b/packages/app/src/components/__tests__/sourceFormPickerDropdowns.test.tsx index b01eafba88..f8873f2040 100644 --- a/packages/app/src/components/__tests__/sourceFormPickerDropdowns.test.tsx +++ b/packages/app/src/components/__tests__/sourceFormPickerDropdowns.test.tsx @@ -1,6 +1,7 @@ import { useForm } from 'react-hook-form'; import { screen, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { fromPartial } from '@total-typescript/shoehorn'; import { useDatabasesDirect, useTablesDirect } from '@/clickhouse'; import { ConnectionSelectControlled } from '@/components/ConnectionSelect'; @@ -28,10 +29,6 @@ jest.mock('../SourceSelect', () => ({ // Mantine's Combobox calls scrollIntoView when its dropdown opens; jsdom lacks it. window.HTMLElement.prototype.scrollIntoView = jest.fn(); -// The hooks return large `UseQueryResult`/connection types; the components only -// read a couple of fields, so cast to a loose mock for these minimal fixtures. -const asMock = (fn: unknown) => fn as jest.Mock; - // Use a large list so the dropdown overflows like the bug report (HDX-4445). const OPTION_COUNT = 20; const databaseNames = Array.from( @@ -48,15 +45,21 @@ const connections = Array.from({ length: OPTION_COUNT }, (_, i) => ({ })); beforeEach(() => { - asMock(useDatabasesDirect).mockReturnValue({ - data: { data: databaseNames.map(name => ({ name })) }, - isLoading: false, - }); - asMock(useTablesDirect).mockReturnValue({ - data: { data: tableNames.map(name => ({ name })) }, - isLoading: false, - }); - asMock(useConnections).mockReturnValue({ data: connections }); + jest.mocked(useDatabasesDirect).mockReturnValue( + fromPartial({ + data: { data: databaseNames.map(name => ({ name })) }, + isLoading: false, + }), + ); + jest.mocked(useTablesDirect).mockReturnValue( + fromPartial({ + data: { data: tableNames.map(name => ({ name })) }, + isLoading: false, + }), + ); + jest + .mocked(useConnections) + .mockReturnValue(fromPartial({ data: connections })); }); function DatabaseHarness() { diff --git a/packages/app/src/hooks/__tests__/useAutoCompleteOptions.test.tsx b/packages/app/src/hooks/__tests__/useAutoCompleteOptions.test.tsx index e54f4433f5..5ebcfaa917 100644 --- a/packages/app/src/hooks/__tests__/useAutoCompleteOptions.test.tsx +++ b/packages/app/src/hooks/__tests__/useAutoCompleteOptions.test.tsx @@ -4,6 +4,7 @@ import { JSDataType } from '@hyperdx/common-utils/dist/clickhouse'; import { Field } from '@hyperdx/common-utils/dist/core/metadata'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { renderHook } from '@testing-library/react'; +import { fromAny, fromPartial } from '@total-typescript/shoehorn'; import { LuceneLanguageFormatter } from '@/components/SearchInput/SearchInputV2'; import { @@ -104,16 +105,20 @@ describe('useAutoCompleteOptions', () => { beforeEach(() => { jest.clearAllMocks(); - (useAllFields as jest.Mock).mockReturnValue({ - data: mockFields, - isLoading: false, - error: null, - }); + jest.mocked(useAllFields).mockReturnValue( + fromPartial({ + data: mockFields, + isLoading: false, + error: null, + }), + ); - (useGetKeyValues as jest.Mock).mockReturnValue({ - data: null, - isFetching: false, - }); + jest.mocked(useGetKeyValues).mockReturnValue( + fromPartial({ + data: undefined, + isFetching: false, + }), + ); wrapper = makeWrapper(); }); @@ -144,15 +149,17 @@ describe('useAutoCompleteOptions', () => { }); it('should return key value options with correct lucene formatting', () => { - (useGetKeyValues as jest.Mock).mockReturnValue({ - data: [ - { - key: 'ResourceAttributes.service.name', - value: ['frontend', 'backend'], - }, - ], - isFetching: false, - }); + jest.mocked(useGetKeyValues).mockReturnValue( + fromPartial({ + data: [ + { + key: 'ResourceAttributes.service.name', + value: ['frontend', 'backend'], + }, + ], + isFetching: false, + }), + ); const { result } = renderHook( () => @@ -191,20 +198,24 @@ describe('useAutoCompleteOptions', () => { }); it('should handle nested key value options', () => { - (useGetKeyValues as jest.Mock).mockReturnValue({ - data: [ - { - key: 'ResourceAttributes', - value: [ - { - 'service.name': 'frontend', - 'deployment.environment': 'production', - }, - ], - }, - ], - isFetching: false, - }); + // Map-typed keys can return object values at runtime, which Facet's + // string[] type does not model. + jest.mocked(useGetKeyValues).mockReturnValue( + fromAny({ + data: [ + { + key: 'ResourceAttributes', + value: [ + { + 'service.name': 'frontend', + 'deployment.environment': 'production', + }, + ], + }, + ], + isFetching: false, + }), + ); const { result } = renderHook( () => diff --git a/packages/app/src/hooks/__tests__/useAvailableMetricNames.test.ts b/packages/app/src/hooks/__tests__/useAvailableMetricNames.test.ts index 0b31f3a8fc..1137357214 100644 --- a/packages/app/src/hooks/__tests__/useAvailableMetricNames.test.ts +++ b/packages/app/src/hooks/__tests__/useAvailableMetricNames.test.ts @@ -9,9 +9,7 @@ import { useGetKeyValues } from '@/hooks/useMetadata'; jest.mock('@/hooks/useMetadata'); -const mockUseGetKeyValues = useGetKeyValues as jest.MockedFunction< - typeof useGetKeyValues ->; +const mockUseGetKeyValues = jest.mocked(useGetKeyValues); const METRIC_SOURCE = { id: 'metric-source-1', diff --git a/packages/app/src/hooks/__tests__/useChartConfig.test.tsx b/packages/app/src/hooks/__tests__/useChartConfig.test.tsx index a20788a176..b5c6535ec9 100644 --- a/packages/app/src/hooks/__tests__/useChartConfig.test.tsx +++ b/packages/app/src/hooks/__tests__/useChartConfig.test.tsx @@ -14,6 +14,7 @@ import { } from '@hyperdx/common-utils/dist/types'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { renderHook, waitFor } from '@testing-library/react'; +import { fromPartial } from '@total-typescript/shoehorn'; import { prometheusApi } from '@/api'; import { useClickhouseClient } from '@/clickhouse'; @@ -390,9 +391,9 @@ describe('useChartConfig', () => { ); - mockClickhouseClient = { + mockClickhouseClient = fromPartial({ queryChartConfig: jest.fn(), - } as unknown as jest.Mocked; + }); jest.mocked(useClickhouseClient).mockReturnValue(mockClickhouseClient); }); diff --git a/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx b/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx index 2f2e4ace05..f516cd93fc 100644 --- a/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx +++ b/packages/app/src/hooks/__tests__/useOffsetPaginatedQuery.test.tsx @@ -143,17 +143,11 @@ describe('useOffsetPaginatedQuery', () => { }; // Reset and set up the mock to return a fresh client each time - ( - getClickhouseClient as jest.MockedFunction - ).mockReset(); - ( - getClickhouseClient as jest.MockedFunction - ).mockReturnValue(mockClickhouseClient); + jest.mocked(getClickhouseClient).mockReset(); + jest.mocked(getClickhouseClient).mockReturnValue(mockClickhouseClient); // Mock renderChartConfig - ( - renderChartConfig as jest.MockedFunction - ).mockResolvedValue({ + jest.mocked(renderChartConfig).mockResolvedValue({ sql: 'SELECT * FROM traces', params: {}, }); diff --git a/scripts/ci/ratchet-baseline.json b/scripts/ci/ratchet-baseline.json index 4a876fb9f5..0f8ebd9218 100644 --- a/scripts/ci/ratchet-baseline.json +++ b/scripts/ci/ratchet-baseline.json @@ -6,7 +6,7 @@ "@source": 0 }, "app": { - "as-any": 199, + "as-any": 184, "ts-ignore": 0, "eslint-disable": 119, "@source": 0