: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { expectLogic } from 'kea-test-utils'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { VisualizationNode, NodeKind, ResultCustomizationBy } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { ChartDisplayType } from '~/types'
import { dataNodeLogic } from '../../DataNode/dataNodeLogic'
import { DataVisualizationLogicProps, dataVisualizationLogic } from '../dataVisualizationLogic'
import { seriesBreakdownLogic } from './seriesBreakdownLogic'
const testUniqueKey = 'testUniqueKey'
const makeInitialQuery = (): VisualizationNode => ({
kind: NodeKind.DataVisualizationNode,
source: {
kind: NodeKind.HogQLQuery,
query: `select event, properties.$browser as browser, count() as total_count from events group by 1, 2`,
},
tableSettings: {
columns: [
{
column: 'event',
settings: {
formatting: {
prefix: '',
suffix: '',
},
},
},
{
column: 'browser',
settings: {
formatting: {
prefix: '',
suffix: '',
},
},
},
{
column: 'total_count',
settings: {
formatting: {
prefix: '',
suffix: '',
},
},
},
],
conditionalFormatting: [],
},
chartSettings: { goalLines: undefined },
})
// globalQuery represents the query object that is passed into the data
// visualization logic and series breakdown logic it is modified by calls to
// setQuery so we want to ensure this is updated correctly
let globalQuery: VisualizationNode = makeInitialQuery()
const dummyDataVisualizationLogicProps: DataVisualizationLogicProps = {
key: testUniqueKey,
query: globalQuery,
setQuery: (setter) => {
globalQuery = setter(globalQuery)
dummyDataVisualizationLogicProps.query = globalQuery
dataVisualizationLogic.build(dummyDataVisualizationLogicProps)
},
editMode: false,
dataNodeCollectionId: 'new-test-SQL',
}
describe('seriesBreakdownLogic', () => {
let logic: ReturnType<typeof seriesBreakdownLogic.build>
let builtDataVizLogic: ReturnType<typeof dataVisualizationLogic.build>
beforeEach(() => {
initKeaTests()
// Mock prefersColorSchemeMedia to avoid TypeError
// (this is a known issue with jest and window.matchMedia)
// and is used by themeLogic
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
dispatchEvent: jest.fn(),
})),
})
featureFlagLogic.mount()
// ensure we reset the globalQuery state before each test
globalQuery = makeInitialQuery()
dummyDataVisualizationLogicProps.query = globalQuery
builtDataVizLogic = dataVisualizationLogic(dummyDataVisualizationLogicProps)
builtDataVizLogic.mount()
})
afterEach(() => {
logic?.unmount()
builtDataVizLogic?.unmount()
})
it('sets the correct values after mounting', async () => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
await expectLogic(logic).toMatchValues({
showSeriesBreakdown: false,
selectedSeriesBreakdownColumn: undefined,
})
expect(globalQuery).toEqual({
...makeInitialQuery(),
chartSettings: {
goalLines: undefined,
seriesBreakdownColumn: undefined,
},
})
})
// this was an example of a previous bug where the series breakdown logic
// would mount and override the existing query settings
it('does not override existing query settings after mounting', async () => {
// set visualization type to line graph and ensure this persists
builtDataVizLogic.actions.setVisualizationType(ChartDisplayType.ActionsLineGraph)
expect(globalQuery.display).toEqual(ChartDisplayType.ActionsLineGraph)
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
await expectLogic(logic).toMatchValues({
showSeriesBreakdown: false,
selectedSeriesBreakdownColumn: undefined,
})
expect(globalQuery).toEqual({
...makeInitialQuery(),
chartSettings: {
goalLines: undefined,
seriesBreakdownColumn: undefined,
},
display: ChartDisplayType.ActionsLineGraph,
})
})
it('adds a series breakdown', async () => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
logic.actions.addSeriesBreakdown('test_column')
await expectLogic(logic).toMatchValues({
showSeriesBreakdown: true,
selectedSeriesBreakdownColumn: 'test_column',
})
expect(globalQuery).toEqual({
...makeInitialQuery(),
chartSettings: {
goalLines: undefined,
seriesBreakdownColumn: 'test_column',
},
})
})
it('adds a series breakdown after mount if one already selected in query', async () => {
builtDataVizLogic.unmount()
globalQuery = {
...makeInitialQuery(),
chartSettings: {
goalLines: undefined,
seriesBreakdownColumn: 'test_column',
},
}
dummyDataVisualizationLogicProps.query = globalQuery
builtDataVizLogic = dataVisualizationLogic(dummyDataVisualizationLogicProps)
builtDataVizLogic.mount()
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
await expectLogic(logic).toMatchValues({
selectedSeriesBreakdownColumn: 'test_column',
showSeriesBreakdown: true,
})
expect(globalQuery).toEqual({
...makeInitialQuery(),
chartSettings: {
goalLines: undefined,
seriesBreakdownColumn: 'test_column',
},
})
})
it('deletes a series breakdown', async () => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
logic.actions.addSeriesBreakdown('test_column')
logic.actions.deleteSeriesBreakdown()
await expectLogic(logic).toMatchValues({
showSeriesBreakdown: false,
selectedSeriesBreakdownColumn: undefined,
})
expect(globalQuery).toEqual({
...makeInitialQuery(),
chartSettings: {
goalLines: undefined,
seriesBreakdownColumn: undefined,
},
})
})
it.each([{ breakdownLogicMounted: true }, { breakdownLogicMounted: false }])(
'deletes a series breakdown when clearAxis is called (breakdown logic mounted: $breakdownLogicMounted)',
async ({ breakdownLogicMounted }) => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
logic.actions.addSeriesBreakdown('test_column')
if (!breakdownLogicMounted) {
logic.unmount()
}
builtDataVizLogic.actions.clearAxis()
await expectLogic(builtDataVizLogic).toFinishAllListeners()
expect(globalQuery).toEqual({
...makeInitialQuery(),
tableSettings: {
columns: [],
conditionalFormatting: [],
},
chartSettings: {
goalLines: undefined,
seriesBreakdownColumn: undefined,
xAxis: undefined,
yAxis: [],
},
})
}
)
it('computes the correct data', async () => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
const builtDataNodeLogic = dataNodeLogic({
key: testUniqueKey,
query: globalQuery.source,
})
builtDataNodeLogic.mount()
builtDataNodeLogic.actions.setResponse({
results: [
['signed_up', 'Safari', 11],
['signed_up', 'Firefox', 22],
['signed_up', 'Chrome', 59],
['logged_out', 'Safari', 32],
['downloaded_file', 'Firefox', 820],
['logged_out', 'Chrome', 173],
['downloaded_file', 'Chrome', 2218],
['downloaded_file', 'Safari', 282],
['logged_out', 'Firefox', 60],
],
columns: ['event', 'browser', 'total_count'],
types: [
['event', 'String'],
['browser', 'Nullable(String)'],
['total_count', 'UInt64'],
],
})
builtDataVizLogic.actions.clearAxis()
builtDataVizLogic.actions.updateXSeries('event')
// The y-axis settings form saves a color by default; breakdown series must not inherit it.
builtDataVizLogic.actions.addYSeries('total_count', {
formatting: { prefix: '', suffix: '' },
display: { color: '#1d4aff' },
})
logic.actions.addSeriesBreakdown('browser')
expect(logic.values.seriesBreakdownData.seriesData.map((series) => series.settings?.display?.color)).toEqual([
undefined,
undefined,
undefined,
])
await expectLogic(logic).toMatchValues({
breakdownColumnValues: ['Safari', 'Firefox', 'Chrome'],
seriesBreakdownData: {
xData: {
column: {
name: 'event',
type: { name: 'STRING', isNumerical: false },
label: 'event - String',
dataIndex: 0,
},
data: ['signed_up', 'logged_out', 'downloaded_file'],
},
seriesData: [
{
name: 'Safari',
breakdownValue: 'Safari',
data: [11, 32, 282],
settings: {
formatting: { prefix: '', suffix: '' },
display: { displayType: undefined, yAxisPosition: undefined },
},
},
{
name: 'Firefox',
breakdownValue: 'Firefox',
data: [22, 60, 820],
settings: {
formatting: { prefix: '', suffix: '' },
display: { displayType: undefined, yAxisPosition: undefined },
},
},
{
name: 'Chrome',
breakdownValue: 'Chrome',
data: [59, 173, 2218],
settings: {
formatting: { prefix: '', suffix: '' },
display: { displayType: undefined, yAxisPosition: undefined },
},
},
],
isUnaggregated: false,
},
})
})
it('applies a custom color to one breakdown value', () => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
const node = dataNodeLogic({ key: testUniqueKey, query: globalQuery.source })
node.mount()
node.actions.setResponse({
results: [
['signed_up', 'Safari', 11],
['signed_up', 'Chrome', 22],
],
columns: ['event', 'browser', 'total_count'],
types: [
['event', 'String'],
['browser', 'String'],
['total_count', 'UInt64'],
],
})
builtDataVizLogic.actions.clearAxis()
builtDataVizLogic.actions.updateXSeries('event')
builtDataVizLogic.actions.addYSeries('total_count')
logic.actions.addSeriesBreakdown('browser')
builtDataVizLogic.actions.updateChartSettings({
resultCustomizations: { Safari: { assignmentBy: ResultCustomizationBy.Value, customColor: '#123456' } },
})
const series = logic.values.seriesBreakdownData.seriesData
expect(series.find((entry) => entry.breakdownValue === 'Safari')?.settings?.display?.color).toBe('#123456')
expect(series.find((entry) => entry.breakdownValue === 'Chrome')?.settings?.display?.color).toBeUndefined()
})
it.each([
{ xColumn: 'event', breakdownColumn: 'browser' },
{ xColumn: 'browser', breakdownColumn: 'event' },
])(
'shows taxonomy display names when the event column is the $xColumn x-axis or $breakdownColumn breakdown',
async ({ xColumn, breakdownColumn }) => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
const builtDataNodeLogic = dataNodeLogic({
key: testUniqueKey,
query: globalQuery.source,
})
builtDataNodeLogic.mount()
builtDataNodeLogic.actions.setResponse({
results: [
['$pageview', 'Safari', 11],
['signed_up', 'Safari', 22],
],
columns: ['event', 'browser', 'total_count'],
types: [
['event', 'String'],
['browser', 'Nullable(String)'],
['total_count', 'UInt64'],
],
})
builtDataVizLogic.actions.clearAxis()
builtDataVizLogic.actions.updateXSeries(xColumn)
builtDataVizLogic.actions.addYSeries('total_count')
logic.actions.addSeriesBreakdown(breakdownColumn)
const { xData, seriesData } = logic.values.seriesBreakdownData
if (xColumn === 'event') {
expect(xData.data).toEqual(['Pageview', 'signed_up'])
expect(seriesData.map((series) => series.name)).toEqual(['Safari'])
} else {
expect(xData.data).toEqual(['Safari'])
expect(seriesData.map((series) => series.name)).toEqual(['Pageview', 'signed_up'])
expect(seriesData.map((series) => series.breakdownValue)).toEqual(['$pageview', 'signed_up'])
}
}
)
it('sums raw breakdown values at zero decimal places', async () => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
const builtDataNodeLogic = dataNodeLogic({
key: testUniqueKey,
query: globalQuery.source,
})
builtDataNodeLogic.mount()
builtDataNodeLogic.actions.setResponse({
results: [
['signed_up', 'Safari', 42.195],
['logged_out', 'Safari', 11.7],
['downloaded_file', 'Safari', 0.49],
['downloaded_file', 'Safari', 0.49],
],
columns: ['event', 'browser', 'total_count'],
types: [
['event', 'String'],
['browser', 'Nullable(String)'],
['total_count', 'Float64'],
],
})
builtDataVizLogic.actions.clearAxis()
builtDataVizLogic.actions.updateXSeries('event')
builtDataVizLogic.actions.addYSeries('total_count')
builtDataVizLogic.actions.updateSeriesIndex(0, 'total_count', { formatting: { decimalPlaces: 0 } })
logic.actions.addSeriesBreakdown('browser')
await expectLogic(logic).toMatchValues({
seriesBreakdownData: expect.objectContaining({
seriesData: [expect.objectContaining({ name: 'Safari', data: [42.195, 11.7, 0.98] })],
}),
})
})
it('preserves missing breakdown buckets as null when showNullsAsZero is disabled', async () => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
const builtDataNodeLogic = dataNodeLogic({
key: testUniqueKey,
query: globalQuery.source,
})
builtDataNodeLogic.mount()
builtDataNodeLogic.actions.setResponse({
results: [
['signed_up', 'Safari', 11],
['logged_out', 'Safari', 32],
['downloaded_file', 'Firefox', 820],
],
columns: ['event', 'browser', 'total_count'],
types: [
['event', 'String'],
['browser', 'Nullable(String)'],
['total_count', 'Nullable(UInt64)'],
],
})
builtDataVizLogic.actions.clearAxis()
builtDataVizLogic.actions.updateXSeries('event')
builtDataVizLogic.actions.addYSeries('total_count')
logic.actions.addSeriesBreakdown('browser')
await expectLogic(logic).toMatchValues({
seriesBreakdownData: {
xData: {
column: {
name: 'event',
type: { name: 'STRING', isNumerical: false },
label: 'event - String',
dataIndex: 0,
},
data: ['signed_up', 'logged_out', 'downloaded_file'],
},
seriesData: [
{
name: 'Safari',
breakdownValue: 'Safari',
data: [11, 32, null],
settings: {
formatting: { prefix: '', suffix: '' },
display: { displayType: undefined, yAxisPosition: undefined },
},
},
{
name: 'Firefox',
breakdownValue: 'Firefox',
data: [null, null, 820],
settings: {
formatting: { prefix: '', suffix: '' },
display: { displayType: undefined, yAxisPosition: undefined },
},
},
],
isUnaggregated: false,
},
})
})
it('renders breakdown nulls as zero when showNullsAsZero is enabled', async () => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
const builtDataNodeLogic = dataNodeLogic({
key: testUniqueKey,
query: globalQuery.source,
})
builtDataNodeLogic.mount()
builtDataNodeLogic.actions.setResponse({
results: [
['signed_up', 'Safari', null],
['logged_out', 'Safari', 32],
['downloaded_file', 'Firefox', 820],
],
columns: ['event', 'browser', 'total_count'],
types: [
['event', 'String'],
['browser', 'Nullable(String)'],
['total_count', 'Nullable(UInt64)'],
],
})
builtDataVizLogic.actions.updateChartSettings({ showNullsAsZero: true })
builtDataVizLogic.actions.clearAxis()
builtDataVizLogic.actions.updateXSeries('event')
builtDataVizLogic.actions.addYSeries('total_count')
logic.actions.addSeriesBreakdown('browser')
await expectLogic(logic).toMatchValues({
seriesBreakdownData: {
xData: {
column: {
name: 'event',
type: { name: 'STRING', isNumerical: false },
label: 'event - String',
dataIndex: 0,
},
data: ['signed_up', 'logged_out', 'downloaded_file'],
},
seriesData: [
{
name: 'Safari',
breakdownValue: 'Safari',
data: [0, 32, 0],
settings: {
formatting: { prefix: '', suffix: '' },
display: { displayType: undefined, yAxisPosition: undefined },
},
},
{
name: 'Firefox',
breakdownValue: 'Firefox',
data: [0, 0, 820],
settings: {
formatting: { prefix: '', suffix: '' },
display: { displayType: undefined, yAxisPosition: undefined },
},
},
],
isUnaggregated: false,
},
})
})
it('caps the breakdown to the top values by total and warns', async () => {
logic = seriesBreakdownLogic({ key: testUniqueKey })
logic.mount()
const builtDataNodeLogic = dataNodeLogic({
key: testUniqueKey,
query: globalQuery.source,
})
builtDataNodeLogic.mount()
// 55 distinct breakdown values across 2 days; the higher the index the higher the total.
const results: [string, string, number][] = []
for (let i = 1; i <= 55; i++) {
results.push(['2026-06-04', `Category ${i}`, i])
results.push(['2026-06-05', `Category ${i}`, i])
}
builtDataNodeLogic.actions.setResponse({
results,
columns: ['event', 'browser', 'total_count'],
types: [
['event', 'String'],
['browser', 'Nullable(String)'],
['total_count', 'UInt64'],
],
})
builtDataVizLogic.actions.clearAxis()
builtDataVizLogic.actions.updateXSeries('event')
builtDataVizLogic.actions.addYSeries('total_count')
logic.actions.addSeriesBreakdown('browser')
await expectLogic(logic).toMatchValues({
breakdownColumnValues: expect.arrayContaining(['Category 1', 'Category 55']),
})
const { seriesBreakdownData } = logic.values
expect(seriesBreakdownData.seriesData).toHaveLength(50)
// Highest-total values are kept, lowest are dropped — including the exact
// cut-off (totals run 1..55, so the top 50 are Category 6..55).
const keptNames = seriesBreakdownData.seriesData.map((series) => series.name)
expect(keptNames).toContain('Category 55')
expect(keptNames).toContain('Category 6')
expect(keptNames).not.toContain('Category 5')
expect(keptNames).not.toContain('Category 1')
expect(seriesBreakdownData.warning).toContain('top 50')
expect(seriesBreakdownData.warning).toContain('55')
})
})