Skip to content

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

29.9 KB
Raw Blame
import { formatAggregationAxisValue } from 'lib/insights/aggregationAxisFormat'
import {
    compareInsightTopLevelSections,
    formatAggregationValue,
    formatBreakdownLabel,
    formatBreakdownType,
    getDisplayNameFromEntityNode,
    getTrendDatasetKey,
    NOT_IN_COHORT_ID,
} from 'scenes/insights/utils'
import { teamLogic } from 'scenes/teamLogic'

import { isEventsNode } from '~/queries/schema/node-guards'
import {
    ActionsNode,
    BreakdownFilter,
    EventsNode,
    InsightQueryNode,
    InsightVizNode,
    NodeKind,
    TrendsQuery,
} from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { BaseMathType, CompareLabelType, TeamType } from '~/types'

import { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'

const createEventsNode = (id?: string | number | null, name?: string, custom_name?: string): EventsNode => {
    return {
        kind: NodeKind.EventsNode,
        custom_name,
        name,
        event: id ? String(id) : undefined,
    }
}

const createActionsNode = (id?: string | number | null, name?: string, custom_name?: string): ActionsNode => {
    return {
        kind: NodeKind.ActionsNode,
        custom_name,
        name,
        id: Number(id),
    }
}

describe('getDisplayNameFromEntityNode()', () => {
    const paramsToExpected: [EventsNode | ActionsNode, boolean, string | null][] = [
        [createEventsNode(3, 'name', 'custom_name'), true, 'custom_name'],
        [createEventsNode(3, 'name', ''), true, 'name'],
        [createEventsNode(3, 'name', '    '), true, 'name'],
        [createEventsNode(3, 'name'), true, 'name'],
        [createEventsNode(3, '', ''), true, '3'],
        [createEventsNode(3, '  ', '    '), true, '3'],
        [createEventsNode(3), true, '3'],
        [createEventsNode('hi'), true, 'hi'],
        [createEventsNode(), true, null],
        [createEventsNode(3, 'name', 'custom_name'), false, 'name'],
        [createEventsNode(3, '  ', 'custom_name'), false, '3'],

        [createActionsNode(3, 'name', 'custom_name'), true, 'custom_name'],
        [createActionsNode(3, 'name', ''), true, 'name'],
        [createActionsNode(3, 'name', '    '), true, 'name'],
        [createActionsNode(3, 'name'), true, 'name'],
        [createActionsNode(3, '', ''), true, '3'],
        [createActionsNode(3, '  ', '    '), true, '3'],
        [createActionsNode(3), true, '3'],
        [createActionsNode(), true, null],
        [createActionsNode(3, 'name', 'custom_name'), false, 'name'],
        [createActionsNode(3, '  ', 'custom_name'), false, '3'],
    ]

    paramsToExpected.forEach(([node, isCustom, expected]) => {
        if (isEventsNode(node)) {
            it(`expect "${expected}" for EventsNode<custom_name="${node.custom_name}", name="${node.name}", event="${node.event}">, isCustom<${isCustom}>`, () => {
                expect(getDisplayNameFromEntityNode(node, isCustom)).toEqual(expected)
            })
        } else {
            it(`expect "${expected}" for ActionsNode<custom_name="${node.custom_name}", name="${node.name}", id="${node.id}">, isCustom<${isCustom}`, () => {
                expect(getDisplayNameFromEntityNode(node, isCustom)).toEqual(expected)
            })
        }
    })

    it('returns null instead of throwing when a series node is null', () => {
        // Malformed insight records can carry a null entry in query.series; the
        // function must not read `.id` off it (caught rendering the saved insights list).
        expect(getDisplayNameFromEntityNode(null as any)).toBeNull()
    })
})

describe('formatAggregationValue', () => {
    it('safely handles null', () => {
        const fakeRenderCount = (x: number): string => String(x)
        const noOpFormatProperty = jest.fn((_, y) => y)
        const actual = formatAggregationValue('some name', null, fakeRenderCount, noOpFormatProperty)
        expect(actual).toEqual('-')
    })

    it('uses render count when there is a value and property format is a no-op', () => {
        const fakeRenderCount = (x: number): string =>
            formatAggregationAxisValue({ aggregationAxisFormat: 'duration' }, x)
        const noOpFormatProperty = jest.fn((_, y) => y)
        const actual = formatAggregationValue('some name', 500, fakeRenderCount, noOpFormatProperty)
        expect(actual).toEqual('8m 20s')
    })

    it('uses render count when there is a value and property format converts number to string', () => {
        const fakeRenderCount = (x: number): string =>
            formatAggregationAxisValue({ aggregationAxisFormat: 'duration' }, x)
        const noOpFormatProperty = jest.fn((_, y) => String(y))
        const actual = formatAggregationValue('some name', 500, fakeRenderCount, noOpFormatProperty)
        expect(actual).toEqual('8m 20s')
    })
})

describe('formatBreakdownLabel()', () => {
    const identity = (_breakdown: any, breakdown_value: any): any => breakdown_value

    const cohort = {
        id: 5,
        name: 'some cohort',
    }

    it('handles cohort breakdowns', () => {
        const breakdownFilter1: BreakdownFilter = {
            breakdown: [cohort.id],
            breakdown_type: 'cohort',
        }
        expect(formatBreakdownLabel(cohort.id, breakdownFilter1, [cohort as any], identity)).toEqual(cohort.name)
    })

    it('falls back to a human-readable label when the cohort is not in the list', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: [3],
            breakdown_type: 'cohort',
        }
        // When the cohorts list isn't loaded/found, never render the bare id — use `Cohort <id>`.
        expect(formatBreakdownLabel(3, breakdownFilter, [], identity)).toEqual('Cohort 3')
        expect(formatBreakdownLabel(3, breakdownFilter, undefined, identity)).toEqual('Cohort 3')
        expect(formatBreakdownLabel('3', breakdownFilter, [], identity)).toEqual('Cohort 3')
    })

    it('resolves the cohort name when the cohort is present in the list', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: [cohort.id],
            breakdown_type: 'cohort',
        }
        expect(formatBreakdownLabel(cohort.id, breakdownFilter, [cohort as any], identity)).toEqual(cohort.name)
    })

    it('handles cohort breakdowns with all users', () => {
        const breakdownFilter1: BreakdownFilter = {
            breakdown: ['all'],
            breakdown_type: 'cohort',
        }
        expect(formatBreakdownLabel('all', breakdownFilter1, [], identity)).toEqual('All Users')

        const breakdownFilter2: BreakdownFilter = {
            breakdown: [0],
            breakdown_type: 'cohort',
        }
        expect(formatBreakdownLabel(0, breakdownFilter2, [], identity)).toEqual('All Users')
    })

    it('handles histogram breakdowns', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: '$browser_version',
            breakdown_type: 'event',
            breakdown_histogram_bin_count: 10,
        }
        expect(formatBreakdownLabel('[124.8,125.01]', breakdownFilter, [], identity)).toEqual('124.8 – 125.01')
    })

    it('handles histogram breakdowns for start and end values', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: '$browser_version',
            breakdown_type: 'event',
            breakdown_histogram_bin_count: 10,
        }
        expect(formatBreakdownLabel('[124.8,124.8]', breakdownFilter, [], identity)).toEqual('124.8')
    })

    it('handles histogram breakdowns for "other" value', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: '$browser_version',
            breakdown_type: 'event',
            breakdown_histogram_bin_count: 10,
        }
        expect(formatBreakdownLabel('$$_posthog_breakdown_other_$$', breakdownFilter, [], identity)).toEqual(
            'Other (i.e. all remaining values)'
        )
    })

    it('handles histogram breakdowns for "null" value', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: '$browser_version',
            breakdown_type: 'event',
            breakdown_histogram_bin_count: 10,
        }
        expect(formatBreakdownLabel('$$_posthog_breakdown_null_$$', breakdownFilter, [], identity)).toEqual(
            'None (i.e. no value)'
        )
    })

    it('handles numeric breakdowns', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: 'coolness_factor',
            breakdown_type: 'event',
        }
        expect(formatBreakdownLabel(42, breakdownFilter, [], identity)).toEqual('42')
    })

    it('skips property-definition formatting for digit-only element breakdown values', () => {
        // element breakdowns (tag_name/text/href) have no matching property definition, so
        // propertyFilterTypeToPropertyDefinitionType falls back to Event. A same-named
        // DateTime/Duration event property must not reformat a numeric-looking element value.
        const reformatsAsDate = (): any => '2020-01-01'
        const breakdownFilter: BreakdownFilter = {
            breakdown: 'text',
            breakdown_type: 'element',
        }
        expect(formatBreakdownLabel('123', breakdownFilter, [], reformatsAsDate)).toEqual('123')
    })

    it('handles numeric breakdowns for "other" value', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: 'coolness_factor',
            breakdown_type: 'event',
        }
        expect(formatBreakdownLabel(9007199254740991, breakdownFilter, [], identity)).toEqual(
            'Other (i.e. all remaining values)'
        )
    })

    it('handles numeric breakdowns for "null" value', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: 'coolness_factor',
            breakdown_type: 'event',
        }
        expect(formatBreakdownLabel(9007199254740990, breakdownFilter, [], identity)).toEqual('None (i.e. no value)')
    })

    it('handles string breakdowns', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: 'demographic',
            breakdown_type: 'event',
        }
        expect(formatBreakdownLabel('millenial', breakdownFilter, [], identity)).toEqual('millenial')
    })

    it('handles string breakdowns for "other" value', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: 'demographic',
            breakdown_type: 'event',
        }
        expect(formatBreakdownLabel('$$_posthog_breakdown_other_$$', breakdownFilter, [], identity)).toEqual(
            'Other (i.e. all remaining values)'
        )
    })

    it('handles string breakdowns for "null" value', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: 'demographic',
            breakdown_type: 'event',
        }
        expect(formatBreakdownLabel('$$_posthog_breakdown_null_$$', breakdownFilter, [], identity)).toEqual(
            'None (i.e. no value)'
        )
    })

    it.each([
        ['exactly 200 chars is not truncated', 'a'.repeat(200), 'a'.repeat(200)],
        ['201 chars is truncated with ellipsis', 'b'.repeat(201), 'b'.repeat(200) + '…'],
        [
            'very long HTML error page is truncated',
            '<html>' + 'x'.repeat(22000) + '</html>',
            '<html>' + 'x'.repeat(194) + '…',
        ],
    ])('truncates long breakdown labels: %s', (_desc, input, expected) => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: 'error_message',
            breakdown_type: 'event',
        }
        expect(formatBreakdownLabel(input, breakdownFilter, [], identity)).toEqual(expected)
    })

    it.each([
        ['201 chars stays intact', 'b'.repeat(201)],
        ['very long HTML error page stays intact', '<html>' + 'x'.repeat(22000) + '</html>'],
    ])('keeps full label when truncation is disabled: %s', (_desc, input) => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: 'error_message',
            breakdown_type: 'event',
        }
        expect(formatBreakdownLabel(input, breakdownFilter, [], identity, undefined, undefined, false)).toEqual(input)
    })

    it('handles multi-breakdowns', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: ['demographic', '$browser'],
            breakdown_type: 'event',
        }
        expect(formatBreakdownLabel(['millenial', 'Chrome'], breakdownFilter, [], identity)).toEqual(
            'millenial::Chrome'
        )
    })

    it('handles multiple breakdowns', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdowns: [
                {
                    property: 'demographic',
                    type: 'event',
                },
                {
                    property: '$browser',
                    type: 'event',
                },
            ],
            breakdown: 'fallback',
        }

        expect(formatBreakdownLabel(['Engineers', 'Chrome'], breakdownFilter, [], identity, 1)).toEqual(
            'Engineers::Chrome'
        )
        expect(formatBreakdownLabel([10, 'Chrome'], breakdownFilter, [], identity, 2)).toEqual('10::Chrome')
        expect(formatBreakdownLabel([10, 'Chrome'], breakdownFilter, [], () => '10s', 0)).toEqual('10s::Chrome')
    })

    it('handles a breakdown value of a multiple breakdown', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdowns: [
                {
                    property: 'demographic',
                    type: 'event',
                },
                {
                    property: '$browser',
                    type: 'event',
                },
            ],
            breakdown: 'fallback',
        }

        expect(formatBreakdownLabel('Chrome', breakdownFilter, [], identity, 1)).toEqual('Chrome')
        expect(formatBreakdownLabel(10, breakdownFilter, [], identity, 2)).toEqual('10')
        expect(formatBreakdownLabel(10, breakdownFilter, [], () => '10s', 0)).toEqual('10s')
    })

    it('handles stringified numbers', () => {
        const formatter = (_breakdown: any, v: any): any => `${v}s`

        const breakdownFilter1: BreakdownFilter = {
            breakdown: '$session_duration',
            breakdown_type: 'session',
        }
        expect(formatBreakdownLabel('661', breakdownFilter1, undefined, formatter)).toEqual('661s')

        const breakdownFilter2: BreakdownFilter = {
            breakdowns: [
                {
                    property: '$session_duration',
                    type: 'session',
                },
            ],
        }
        expect(formatBreakdownLabel('661', breakdownFilter2, undefined, formatter, 0)).toEqual('661s')
    })

    it('handles large stringified numbers', () => {
        const formatter = (_breakdown: any, v: any): any => `${v}s`

        const breakdownFilter1: BreakdownFilter = {
            breakdown: '$session_duration',
            breakdown_type: 'session',
        }
        expect(formatBreakdownLabel('661', breakdownFilter1, undefined, formatter)).toEqual('661s')

        const breakdownFilter2: BreakdownFilter = {
            breakdowns: [
                {
                    property: '$session_duration',
                    type: 'session',
                },
            ],
        }
        expect(formatBreakdownLabel('987654321012345678', breakdownFilter2, undefined, formatter, 0)).toEqual(
            '987654321012345678s'
        )
    })

    it('handles array first', () => {
        const formatter = (_: any, value: any, type: any): any => (type === 'session' ? `${value}s` : value)

        const breakdownFilter1: BreakdownFilter = {
            breakdown: '$session_duration',
            breakdown_type: 'session',
        }
        expect(formatBreakdownLabel(['661'], breakdownFilter1, undefined, formatter)).toEqual('661s')

        const breakdownFilter2: BreakdownFilter = {
            breakdowns: [
                {
                    property: '$session_duration',
                    type: 'session',
                },
            ],
        }
        expect(formatBreakdownLabel('661', breakdownFilter2, undefined, formatter, 0)).toEqual('661s')
    })

    it('handles group breakdowns', () => {
        const formatter = jest.fn((_, v) => v)

        const breakdownFilter1: BreakdownFilter = {
            breakdown: 'name',
            breakdown_group_type_index: 0,
            breakdown_type: 'group',
        }
        expect(formatBreakdownLabel('661', breakdownFilter1, undefined, formatter)).toEqual('661')
        expect(formatter).toHaveBeenCalledWith('name', 661, 'group', 0)

        formatter.mockClear()

        const breakdownFilter2: BreakdownFilter = {
            breakdowns: [{ property: 'name', type: 'group', group_type_index: 0 }],
        }
        expect(formatBreakdownLabel(['661'], breakdownFilter2, undefined, formatter, 0)).toEqual('661')
        expect(formatter).toHaveBeenCalledWith('name', 661, 'group', 0)

        formatter.mockClear()

        const breakdownFilter3: BreakdownFilter = {
            breakdowns: [
                { property: 'name', type: 'group', group_type_index: 0 },
                { property: 'test', type: 'group', group_type_index: 1 },
            ],
        }
        expect(formatBreakdownLabel(['661', '662'], breakdownFilter3, undefined, formatter, 0)).toEqual('661::662')
        expect(formatter).toHaveBeenNthCalledWith(1, 'name', 661, 'group', 0)
        expect(formatter).toHaveBeenNthCalledWith(2, 'test', 662, 'group', 1)
    })

    it('handles not-in-cohort complement with cohort name', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: [cohort.id],
            breakdown_type: 'cohort',
        }
        expect(formatBreakdownLabel(NOT_IN_COHORT_ID, breakdownFilter, [cohort as any], identity)).toEqual(
            'Not in some cohort'
        )
    })

    it('handles not-in-cohort complement without matching cohort', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: [999],
            breakdown_type: 'cohort',
        }
        expect(formatBreakdownLabel(NOT_IN_COHORT_ID, breakdownFilter, [], identity)).toEqual('Not in cohort')
    })

    it('handles not-in-cohort complement as stringified number', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown: [cohort.id],
            breakdown_type: 'cohort',
        }
        expect(formatBreakdownLabel(String(NOT_IN_COHORT_ID), breakdownFilter, [cohort as any], identity)).toEqual(
            'Not in some cohort'
        )
    })

    it('handles breakdown cohort that has no breakdown_type', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdowns: [
                {
                    property: 1,
                    type: 'cohort',
                },
                {
                    property: 5,
                    type: 'cohort',
                },
            ],
        }
        const multipleBreakdownIndex = 1
        expect(
            formatBreakdownLabel(cohort.id, breakdownFilter, [cohort as any], identity, multipleBreakdownIndex)
        ).toEqual(cohort.name)
    })
})

describe('formatBreakdownType()', () => {
    it('handles regular breakdowns', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown_type: 'event',
            breakdown: '$current_url',
            breakdown_normalize_url: true,
        }

        expect(formatBreakdownType(breakdownFilter)).toEqual('$current_url')
    })

    it('handles cohort breakdowns', () => {
        const breakdownFilter: BreakdownFilter = {
            breakdown_type: 'cohort',
            breakdown: ['all', 1],
        }

        expect(formatBreakdownType(breakdownFilter)).toEqual('Cohort')
    })
})

describe('getTrendDatasetKey()', () => {
    const seriesQuery: TrendsQuery = {
        kind: NodeKind.TrendsQuery,
        series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
    }
    const formulaQuery: TrendsQuery = {
        ...seriesQuery,
        series: [
            { kind: NodeKind.EventsNode, event: '$pageview' },
            { kind: NodeKind.EventsNode, event: '$autocapture' },
        ],
        trendsFilter: { formulaNodes: [{ formula: 'A+B' }, { formula: 'A-B' }] },
    }

    it('handles a simple insight', () => {
        const dataset: Partial<IndexedTrendResult> = { label: '$pageview', order: 0 }

        expect(getTrendDatasetKey(dataset as IndexedTrendResult, seriesQuery)).toEqual('{"series":0}')
    })

    it('handles insights with breakdowns', () => {
        const dataset: Partial<IndexedTrendResult> = {
            label: 'Opera::US',
            order: 0,
            breakdown_value: ['Opera', 'US'],
        }

        expect(getTrendDatasetKey(dataset as IndexedTrendResult, seriesQuery)).toEqual(
            '{"series":0,"breakdown_value":["Opera","US"]}'
        )
    })

    it('ignores compare periods, so that current and previous share a key', () => {
        const current: Partial<IndexedTrendResult> = {
            label: '$pageview',
            order: 0,
            compare: true,
            compare_label: CompareLabelType.Current,
        }
        const previous: Partial<IndexedTrendResult> = { ...current, compare_label: CompareLabelType.Previous }

        expect(getTrendDatasetKey(current as IndexedTrendResult, seriesQuery)).toEqual('{"series":0}')
        expect(getTrendDatasetKey(previous as IndexedTrendResult, seriesQuery)).toEqual('{"series":0}')
    })

    it('keys a formula by its position, not the series its order would index', () => {
        // a formula row's order indexes the formulas, so the second formula carries order 1
        const dataset: Partial<IndexedTrendResult> = {
            label: 'Formula (A-B)',
            order: 1,
            seriesIndex: 1,
            colorIndex: 1,
        }

        expect(getTrendDatasetKey(dataset as IndexedTrendResult, formulaQuery)).toEqual('{"series":"formula2"}')
    })

    it('keys compare periods of a formula by their shared position, not the raw series index', () => {
        // with compare enabled, previous-period datasets have offset series indexes
        // (e.g. 2 for the previous period of the first of two formulas), but share
        // the colorIndex with their current-period counterpart
        const previous: Partial<IndexedTrendResult> = {
            label: 'Formula (A+B)',
            order: 0,
            seriesIndex: 2,
            colorIndex: 0,
            compare: true,
            compare_label: CompareLabelType.Previous,
        }

        expect(getTrendDatasetKey(previous as IndexedTrendResult, formulaQuery)).toEqual('{"series":"formula"}')
    })

    it('handles insights with non-array breakdown values', () => {
        const dataset: Partial<IndexedTrendResult> = { label: 'Opera', order: 0, breakdown_value: 'Opera' }

        expect(getTrendDatasetKey(dataset as IndexedTrendResult, seriesQuery)).toEqual(
            '{"series":0,"breakdown_value":["Opera"]}'
        )
    })
})

describe('compareTopLevelSections()', () => {
    beforeEach(() => {
        initKeaTests()
    })

    it('compares top-level sections', () => {
        const obj1: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
            interval: 'day',
        }
        const obj2: InsightQueryNode = {
            kind: NodeKind.FunnelsQuery,
            series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
            interval: 'day',
        }

        expect(compareInsightTopLevelSections(obj1, obj2)).toEqual(['Insight type'])
    })

    it('compares source fields', () => {
        const obj1: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [],
            interval: 'day',
        }
        const obj2: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [],
            interval: 'week',
        }

        expect(compareInsightTopLevelSections(obj1, obj2)).toEqual(['Interval'])
    })

    it('compares multiple source fields', () => {
        const obj1: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [],
            interval: 'day',
            breakdownFilter: undefined,
            dateRange: { date_from: '-7d' },
        }
        const obj2: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [],
            interval: 'week',
            breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },
            dateRange: { date_from: '-30d' },
        }

        expect(compareInsightTopLevelSections(obj1, obj2)).toEqual(['Breakdowns', 'Date range', 'Interval'])
    })

    it('handles unknown source fields', () => {
        const obj1 = { kind: NodeKind.TrendsQuery, series: [], unknownField: 'value1' } as any
        const obj2 = { kind: NodeKind.TrendsQuery, series: [], unknownField: 'value2' } as any

        expect(compareInsightTopLevelSections(obj1, obj2)).toEqual(['unknownField'])
    })

    it('handles nested objects in source fields', () => {
        const obj1: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [],
            breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },
        }
        const obj2: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [],
            breakdownFilter: { breakdown: '$os', breakdown_type: 'event' },
        }

        expect(compareInsightTopLevelSections(obj1, obj2)).toEqual(['Breakdowns'])
    })

    it('handles arrays in source fields', () => {
        const obj1: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
        }
        const obj2: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [
                { kind: NodeKind.EventsNode, event: '$pageview' },
                { kind: NodeKind.EventsNode, event: '$autocapture' },
            ],
        }

        expect(compareInsightTopLevelSections(obj1, obj2)).toEqual(['Series'])
    })

    it('returns empty array when no differences', () => {
        const obj1: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [],
            interval: 'day',
        }
        const obj2: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [],
            interval: 'day',
        }

        expect(compareInsightTopLevelSections(obj1, obj2)).toEqual([])
    })

    it('handles arrays with same elements in different order', () => {
        const obj1: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [
                { kind: NodeKind.EventsNode, event: '$pageview' },
                { kind: NodeKind.EventsNode, event: '$autocapture' },
            ],
        }
        const obj2: InsightQueryNode = {
            kind: NodeKind.TrendsQuery,
            series: [
                { kind: NodeKind.EventsNode, event: '$autocapture' },
                { kind: NodeKind.EventsNode, event: '$pageview' },
            ],
        }

        expect(compareInsightTopLevelSections(obj1, obj2)).toEqual([])
    })

    it('ignores query plumbing and empty sections on a wrapped insight query', () => {
        const previous: InsightVizNode = {
            kind: NodeKind.InsightVizNode,
            source: {
                kind: NodeKind.TrendsQuery,
                version: 3,
                series: [{ kind: NodeKind.EventsNode, event: '$pageview', math: BaseMathType.TotalCount }],
                trendsFilter: {},
                tags: { productKey: 'product_analytics' },
            },
        }
        const suggested: InsightVizNode = {
            kind: NodeKind.InsightVizNode,
            source: {
                kind: NodeKind.TrendsQuery,
                series: [{ kind: NodeKind.EventsNode, event: '$pageleave' }],
            },
        }

        expect(compareInsightTopLevelSections(previous, suggested)).toEqual(['Series'])
    })

    it('reports a modifiers change when the current query overrides the team default', () => {
        teamLogic.mount()

        const previous: InsightVizNode = {
            kind: NodeKind.InsightVizNode,
            source: {
                kind: NodeKind.TrendsQuery,
                series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
                modifiers: { personsOnEventsMode: 'person_id_override_properties_joined' },
            },
        }
        const suggested: InsightVizNode = {
            kind: NodeKind.InsightVizNode,
            source: {
                kind: NodeKind.TrendsQuery,
                series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
            },
        }

        expect(compareInsightTopLevelSections(previous, suggested)).toEqual(['Query modifiers'])

        teamLogic.unmount()
    })

    it('ignores modifiers that match the team default', () => {
        teamLogic.mount()
        teamLogic.actions.loadCurrentTeamSuccess({
            id: 1,
            modifiers: { personsOnEventsMode: 'person_id_override_properties_joined' },
        } as unknown as TeamType)

        const previous: InsightVizNode = {
            kind: NodeKind.InsightVizNode,
            source: {
                kind: NodeKind.TrendsQuery,
                series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
                modifiers: { personsOnEventsMode: 'person_id_override_properties_joined' },
            },
        }
        const suggested: InsightVizNode = {
            kind: NodeKind.InsightVizNode,
            source: {
                kind: NodeKind.TrendsQuery,
                series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
            },
        }

        expect(compareInsightTopLevelSections(previous, suggested)).toEqual([])

        teamLogic.unmount()
    })

    it('handles null/undefined objects', () => {
        expect(
            compareInsightTopLevelSections(null as any, { kind: NodeKind.TrendsQuery, series: [] } as InsightQueryNode)
        ).toEqual(['Insight type'])
        expect(
            compareInsightTopLevelSections({ kind: NodeKind.TrendsQuery, series: [] } as InsightQueryNode, null as any)
        ).toEqual(['Insight type'])
        expect(compareInsightTopLevelSections(null as any, null as any)).toEqual([])
    })
})