: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 { MOCK_DEFAULT_TEAM, MOCK_TEAM_ID } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic, partial, truth } from 'kea-test-utils'
import posthog from 'posthog-js'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { objectsEqual } from 'lib/utils/objects'
import 'lib/constants'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { liveDashboardIds } from 'scenes/dashboard/liveDashboardIds'
import { savedInsightsLogic } from 'scenes/saved-insights/savedInsightsLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { dashboardsModel } from '~/models/dashboardsModel'
import { insightsModel } from '~/models/insightsModel'
import { tagsModel } from '~/models/tagsModel'
import { examples } from '~/queries/examples'
import { DataTableNode, type InsightVizNode, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import {
AccessControlLevel,
AnyPropertyFilter,
BaseMathType,
DashboardTile,
DashboardType,
FilterLogicalOperator,
FilterType,
InsightLogicProps,
InsightShortId,
InsightType,
PropertyFilterType,
PropertyOperator,
InsightModel,
} from '~/types'
import { insightDataLogic } from './insightDataLogic'
import { createEmptyInsight, insightLogic } from './insightLogic'
import { insightVizDataLogic } from './insightVizDataLogic'
import { insightsApi } from './utils/api'
const API_FILTERS: Partial<FilterType> = {
insight: InsightType.TRENDS as InsightType,
properties: [{ value: 'a', operator: PropertyOperator.Exact, key: 'a', type: 'a' } as any as AnyPropertyFilter],
}
const API_QUERY = {
kind: NodeKind.InsightVizNode,
source: {
kind: NodeKind.TrendsQuery,
series: [{ kind: NodeKind.EventsNode, event: 3, math: 'total' }],
properties: {
type: 'AND',
values: [{ type: 'AND', values: [{ key: 'a', type: 'a', value: 'a', operator: PropertyOperator.Exact }] }],
},
},
}
const Insight12 = '12' as InsightShortId
const Insight42 = '42' as InsightShortId
const Insight43 = '43' as InsightShortId
const Insight44 = '44' as InsightShortId
const MOCK_DASHBOARD_ID = 34
const partialInsight42 = {
id: 42,
short_id: Insight42,
result: ['result 42'],
filters: API_FILTERS,
}
const partialInsight43 = {
id: 43,
short_id: Insight43,
result: ['result 43'],
filters: API_FILTERS,
}
const partialInsight44 = {
id: 44,
short_id: Insight44,
result: ['result 44'],
filters: API_FILTERS,
}
const TILES_ON_DASHBOARDS_1_2_3 = [
{ id: 11, dashboard_id: 1 },
{ id: 12, dashboard_id: 2 },
{ id: 13, dashboard_id: 3 },
]
const patchResponseFor = (id: string, filters: Record<string, any>): Record<string, any> => {
return {
result: id === '42' ? ['result from api'] : null,
id: id === '42' ? 42 : 43,
short_id: id === '42' ? Insight42 : Insight43,
filters: filters || API_FILTERS,
name: id === '42' ? undefined : 'Foobar 43',
description: id === '42' ? undefined : 'Lorem ipsum.',
tags: id === '42' ? undefined : ['good'],
dashboard_tiles: id === '43' ? [{ dashboard_id: MOCK_DASHBOARD_ID }] : undefined,
}
}
function insightModelWith(properties: Record<string, any>): InsightModel {
return {
id: 42,
short_id: Insight42,
result: ['result 42'],
query: API_QUERY,
dashboard_tiles: [],
saved: true,
name: 'new name',
order: null,
last_refresh: null,
created_at: '2021-03-09T14: 00: 00.000Z',
created_by: null,
deleted: false,
description: '',
is_sample: false,
is_shared: null,
pinned: null,
refresh_interval: null,
updated_at: '2021-03-09T14: 00: 00.000Z',
updated_by: null,
visibility: null,
last_modified_at: '2021-03-31T15:00:00.000Z',
last_modified_by: null,
layouts: {},
color: null,
user_access_level: AccessControlLevel.Editor,
...properties,
} as InsightModel
}
const seenQueryIDs: string[] = []
describe('insightLogic', () => {
let logic: ReturnType<typeof insightLogic.build>
beforeEach(async () => {
useMocks({
get: {
'/api/projects/:team/tags': [],
'/api/environments/:team_id/quick_filters/': {
results: [],
},
'/api/environments/:team_id/insights/trend/': async ({ request }) => {
const url = new URL(request.url)
const clientQueryId = url.searchParams.get('client_query_id')
if (clientQueryId !== null) {
seenQueryIDs.push(clientQueryId)
}
if (JSON.parse(url.searchParams.get('events') || '[]')?.[0]?.throw) {
return [500, { status: 0, detail: 'error from the API' }]
}
if (url.searchParams.get('date_from') === '-180d') {
// delay for 2 seconds before response without pausing
return new Promise<[number, { result: string[] }]>((resolve) =>
setTimeout(() => {
resolve([200, { result: ['very slow result from api'] }])
}, 2000)
)
}
return [200, { result: ['result from api'] }]
},
'/api/environments/:team_id/insights/path/': { result: ['result from api'] },
'/api/environments/:team_id/insights/path': { result: ['result from api'] },
'/api/environments/:team_id/insights/funnel/': { result: ['result from api'] },
'/api/environments/:team_id/insights/retention/': { result: ['result from api'] },
'/api/environments/:team_id/insights/42': partialInsight42,
'/api/environments/:team_id/insights/43/': partialInsight43,
'/api/environments/:team_id/insights/44/': partialInsight44,
'/api/environments/:team_id/insights/': ({ request }) => {
const url = new URL(request.url)
if (url.searchParams.get('saved')) {
return [
200,
{
results: [
{
id: 42,
short_id: Insight42,
result: ['result 42'],
filters: API_FILTERS,
name: 'original name',
dashboard_tiles: TILES_ON_DASHBOARDS_1_2_3,
},
{ id: 43, short_id: Insight43, result: ['result 43'], filters: API_FILTERS },
],
},
]
}
const shortId = url.searchParams.get('short_id') || ''
if (shortId === '500') {
return [500, { status: 0, detail: 'error from the API' }]
}
return [
200,
{
results: [
{
result: parseInt(shortId) === 42 ? ['result from api'] : null,
id: parseInt(shortId),
short_id: shortId.toString(),
filters: JSON.parse(url.searchParams.get('filters') || 'false') || API_FILTERS,
name: 'original name',
dashboard_tiles: TILES_ON_DASHBOARDS_1_2_3,
},
],
},
]
},
'/api/environments/:team_id/dashboards/33/': {
id: 33,
filters: {},
tiles: [
{
layouts: {},
color: null,
insight: {
id: 42,
short_id: Insight42,
result: 'result!',
filters: { insight: InsightType.TRENDS, interval: 'month' },
tags: ['bla'],
},
},
],
},
'/api/environments/:team_id/dashboards/34/': {
id: 33,
filters: {},
tiles: [
{
layouts: {},
color: null,
insight: {
id: 42,
short_id: Insight43,
result: 'result!',
filters: { insight: InsightType.TRENDS, interval: 'month' },
tags: ['bla'],
},
},
],
},
},
post: {
'/api/environments/:team_id/insights/funnel/': { result: ['result from api'] },
'/api/environments/:team_id/insights/viewed': [201],
'/api/environments/:team_id/insights/': async ({ request }) => [
200,
{ ...((await request.json()) as any), id: 12, short_id: Insight12 },
],
'/api/environments/997/insights/cancel/': [201],
},
patch: {
'/api/environments/:team_id/insights/:id': async ({ request, params }) => {
const response = patchResponseFor(
params.id as string,
JSON.parse(new URL(request.url).searchParams.get('filters') || 'false')
)
return [200, response]
},
},
})
initKeaTests(true, { ...MOCK_DEFAULT_TEAM, test_account_filters_default_checked: true })
teamLogic.mount()
sceneLogic.mount()
await expectLogic(teamLogic)
.toFinishAllListeners()
.toMatchValues({ currentTeam: partial({ test_account_filters_default_checked: true }) })
insightsModel.mount()
})
it('requires props', () => {
expect(() => {
insightLogic()
}).toThrow('Must init with dashboardItemId, even if undefined')
})
describe('when there is no props id', () => {
it('has the key set to "new"', () => {
logic = insightLogic({
dashboardItemId: undefined,
})
expect(logic.key).toEqual('new')
})
})
describe('as dashboard item', () => {
describe('props with filters and cached results', () => {
beforeEach(() => {
logic = insightLogic({
dashboardItemId: Insight42,
cachedInsight: {
short_id: Insight42,
results: ['cached result'],
filters: {
insight: InsightType.TRENDS,
events: [{ id: 2 }],
properties: [
{
value: 'lol',
operator: PropertyOperator.Exact,
key: 'lol',
type: PropertyFilterType.Person,
},
],
},
},
})
logic.mount()
})
it('has the key set to the id', () => {
expect(logic.key).toEqual('42')
})
})
describe('props with query and cached results', () => {
beforeEach(() => {
logic = insightLogic({
dashboardItemId: Insight42,
cachedInsight: {
short_id: Insight42,
results: ['cached result'],
filters: {},
query: { kind: NodeKind.EventsQuery },
},
})
logic.mount()
})
it('has the key set to the id', () => {
expect(logic.key).toEqual('42')
})
})
describe('props with query, no cached results', () => {
it('still does not make a query to load the results', async () => {
logic = insightLogic({
dashboardItemId: Insight42,
cachedInsight: {
short_id: Insight42,
results: undefined,
filters: {},
query: { kind: NodeKind.EventsQuery },
},
})
logic.mount()
await expectLogic(logic)
.toDispatchActions([])
.toMatchValues({
insight: partial({
short_id: Insight42,
query: { kind: NodeKind.EventsQuery },
}),
})
.delay(1)
// do not override the insight if querying with different filters
.toNotHaveDispatchedActions(['updateInsight', 'updateInsightSuccess'])
})
})
describe('props with filters, no cached results, respects doNotLoad', () => {
it('does not make a query', async () => {
const insight: Partial<InsightModel<InsightVizNode>> = {
short_id: Insight42,
query: {
kind: NodeKind.InsightVizNode,
source: {
kind: NodeKind.TrendsQuery,
series: [{ kind: NodeKind.EventsNode, event: '3', math: BaseMathType.TotalCount }],
properties: {
type: FilterLogicalOperator.And,
values: [
{
type: FilterLogicalOperator.And,
values: [
{
value: 'a',
operator: PropertyOperator.Exact,
key: 'a',
type: PropertyFilterType.Person,
},
],
},
],
},
},
},
}
logic = insightLogic({
dashboardItemId: Insight42,
cachedInsight: insight,
doNotLoad: true,
})
logic.mount()
await expectLogic(logic)
.toMatchValues({
insight: {
short_id: Insight42,
query: {
kind: 'InsightVizNode',
source: {
kind: 'TrendsQuery',
properties: {
type: 'AND',
values: [
{
type: 'AND',
values: [partial({ value: 'a' })],
},
],
},
series: [partial({ event: '3' })],
},
},
},
})
.delay(1)
.toNotHaveDispatchedActions(['setFilters', 'updateInsight'])
})
})
})
describe('takes data from other logics if available', () => {
it.each([true, false])('only fetches the definition when notebook retention is %s', async (retain) => {
const requests: URL[] = []
useMocks({
get: {
'/api/environments/:team_id/insights/': ({ request }) => {
requests.push(new URL(request.url))
return { results: [insightModelWith({})] }
},
},
})
logic = insightLogic({ dashboardItemId: Insight42, retainResponseOnUnmount: retain })
logic.mount()
await expectLogic(logic).toDispatchActions(['loadInsightSuccess'])
expect(requests).toHaveLength(1)
expect(requests[0].searchParams.get('basic')).toBe(retain ? 'true' : null)
logic.unmount()
logic = insightLogic({ dashboardItemId: Insight42, retainResponseOnUnmount: retain })
logic.mount()
expect(!!logic.values.insight.query).toBe(retain)
await expectLogic(logic).toDispatchActions(['loadInsightSuccess'])
})
const verifyItLoadsFromTheAPI = async (logicUnderTest: ReturnType<typeof insightLogic.build>): Promise<void> =>
expectLogic(logicUnderTest)
.toDispatchActions(['loadInsight'])
.toMatchValues({
insight: partial({
short_id: '42',
}),
})
it('loads from the api when coming from dashboard context', async () => {
// 1. the dashboard is mounted
const dashLogic = dashboardLogic({ id: 33 })
dashLogic.mount()
await expectLogic(dashLogic).toDispatchActions(['loadDashboardSuccess'])
// 2. mount the insight
logic = insightLogic({ dashboardItemId: Insight42, dashboardId: 33 })
logic.mount()
await verifyItLoadsFromTheAPI(logic)
})
it('does not load from the dashboardLogic when not in that dashboard context', async () => {
// 1. the dashboard is mounted
const dashLogic = dashboardLogic({ id: 33 })
dashLogic.mount()
await expectLogic(dashLogic).toDispatchActions(['loadDashboardSuccess'])
// 2. mount the insight
logic = insightLogic({ dashboardItemId: Insight42, dashboardId: 1 })
logic.mount()
await verifyItLoadsFromTheAPI(logic)
})
it('does not load from the savedInsightLogic when in a dashboard context', async () => {
// 1. open saved insights
router.actions.push(urls.savedInsights(), {}, {})
savedInsightsLogic().mount()
// 2. the insights are loaded
await expectLogic(savedInsightsLogic()).toDispatchActions(['loadInsights', 'loadInsightsSuccess'])
// 3. mount the insight
logic = insightLogic({ dashboardItemId: Insight42, dashboardId: 33 })
logic.mount()
await verifyItLoadsFromTheAPI(logic)
})
})
test('keeps saved name, description, tags', async () => {
const insightProps: InsightLogicProps = {
dashboardItemId: Insight43,
cachedInsight: { ...createEmptyInsight(Insight43), id: 123, query: API_QUERY },
}
logic = insightLogic(insightProps)
logic.mount()
insightDataLogic(insightProps).mount()
const expectedPartialInsight = {
name: undefined,
description: '',
tags: [],
query: partial({
source: partial({
series: [{ event: 3, kind: NodeKind.EventsNode, math: 'total' }],
kind: NodeKind.TrendsQuery,
properties: {
type: 'AND',
values: [{ type: 'AND', values: [{ key: 'a', operator: 'exact', type: 'a', value: 'a' }] }],
},
}),
}),
}
await expectLogic(logic).toMatchValues({
insight: partial(expectedPartialInsight),
savedInsight: partial(expectedPartialInsight),
insightChanged: false,
})
await expectLogic(logic, () => {
logic.actions.setInsightMetadataLocal({ name: 'Foobar 43', description: 'Lorem ipsum.', tags: ['good'] })
}).toMatchValues({
insight: partial({ name: 'Foobar 43', description: 'Lorem ipsum.', tags: ['good'] }),
savedInsight: partial({ name: undefined, description: '', tags: [] }),
insightChanged: true,
})
await expectLogic(logic, () => {
logic.actions.saveInsight()
}).toFinishAllListeners()
await expectLogic(logic).toMatchValues({
insight: partial({ name: 'Foobar 43', description: 'Lorem ipsum.', tags: ['good'] }),
savedInsight: partial({ name: 'Foobar 43', description: 'Lorem ipsum.', tags: ['good'] }),
insightChanged: false,
})
})
test('saveInsight saves new insight and redirects to view mode', async () => {
const insightProps: InsightLogicProps = {
dashboardItemId: 'new',
}
logic = insightLogic(insightProps)
logic.mount()
insightDataLogic(insightProps).mount()
await expectLogic(logic, () => {
logic.actions.saveInsight()
}).toDispatchActions(['saveInsight', router.actionCreators.push(urls.insightView(Insight12))])
})
test('saveInsight and updateInsight update the saved insights list', async () => {
savedInsightsLogic().mount()
const insightProps: InsightLogicProps = {
dashboardItemId: Insight42,
cachedInsight: {
short_id: Insight42,
query: examples.FunnelsQuery,
result: {},
},
}
logic = insightLogic(insightProps)
logic.mount()
insightDataLogic(insightProps).mount()
logic.actions.saveInsight()
await expectLogic(logic).toDispatchActions([savedInsightsLogic().actionTypes.addInsight])
logic.actions.updateInsight({ name: 'my new name' })
await expectLogic(logic).toDispatchActions([savedInsightsLogic().actionTypes.updateInsight])
})
test('saveInsight clears the browser draft only when saving a new insight', async () => {
const draftKey = `draft-query-${MOCK_TEAM_ID}`
localStorage.setItem(draftKey, JSON.stringify({ query: { kind: 'TrendsQuery' }, timestamp: 1 }))
const updateProps: InsightLogicProps = {
dashboardItemId: Insight42,
cachedInsight: { id: 42, short_id: Insight42, query: examples.FunnelsQuery, result: {} },
}
logic = insightLogic(updateProps)
logic.mount()
insightDataLogic(updateProps).mount()
await expectLogic(logic, () => {
logic.actions.saveInsight()
}).toFinishAllListeners()
expect(localStorage.getItem(draftKey)).not.toBeNull()
const newProps: InsightLogicProps = { dashboardItemId: 'new' }
logic = insightLogic(newProps)
logic.mount()
insightDataLogic(newProps).mount()
await expectLogic(logic, () => {
logic.actions.saveInsight()
}).toFinishAllListeners()
expect(localStorage.getItem(draftKey)).toBeNull()
})
test('saveInsight updates dashboards', async () => {
const dashLogic = dashboardLogic({ id: MOCK_DASHBOARD_ID })
dashLogic.mount()
await expectLogic(dashLogic).toDispatchActions(['loadDashboard'])
savedInsightsLogic().mount()
const insightProps: InsightLogicProps = {
dashboardItemId: Insight43,
}
logic = insightLogic(insightProps)
logic.mount()
insightDataLogic(insightProps).mount()
logic.actions.saveInsight()
await expectLogic(dashLogic).toDispatchActions(['loadDashboard'])
})
const savedInsightProps: InsightLogicProps = {
dashboardItemId: Insight42,
cachedInsight: {
id: 42,
short_id: Insight42,
query: examples.FunnelsQuery,
result: {},
dashboard_tiles: TILES_ON_DASHBOARDS_1_2_3,
},
}
const newDashboardInsightProps: InsightLogicProps = {
dashboardItemId: 'new',
cachedInsight: { ...createEmptyInsight('new'), dashboards: [MOCK_DASHBOARD_ID] },
}
test.each([
{
name: 'a saved insight stays on the dashboards it sits on',
insightProps: savedInsightProps,
tileGroup: null,
expectedPlacements: [],
expectedGroupWrites: [],
},
{
name: 'a saved insight opened from a tile group link keeps its tiles where they are',
insightProps: savedInsightProps,
tileGroup: 'target',
expectedPlacements: [],
expectedGroupWrites: [],
},
{
name: 'a new insight goes on the dashboard it was started from',
insightProps: newDashboardInsightProps,
tileGroup: null,
expectedPlacements: [[12, MOCK_DASHBOARD_ID]],
expectedGroupWrites: [],
},
{
name: 'a new insight started from a tile group goes into that group',
insightProps: newDashboardInsightProps,
tileGroup: 'target',
expectedPlacements: [[12, MOCK_DASHBOARD_ID]],
expectedGroupWrites: [{ tiles: [{ id: 99, group_key: 'target' }] }],
},
] as {
name: string
insightProps: InsightLogicProps
tileGroup: string | null
expectedPlacements: number[][]
expectedGroupWrites: unknown[]
}[])('saving: $name', async ({ insightProps, tileGroup, expectedPlacements, expectedGroupWrites }) => {
const groupWrites: unknown[] = []
useMocks({
patch: {
[`/api/environments/:team_id/dashboards/${MOCK_DASHBOARD_ID}/`]: async ({ request }) => {
groupWrites.push(await request.json())
return [200, {}]
},
},
})
router.actions.push('/insights/new', tileGroup ? { tile_group: tileGroup } : {})
const update = jest.spyOn(api, 'update')
const create = jest.spyOn(api, 'create')
const addToDashboard = jest
.spyOn(insightsApi, 'addToDashboard')
.mockImplementation(async (_insightId, dashboardId) => ({ id: 99, dashboard_id: dashboardId }))
logic = insightLogic(insightProps)
logic.mount()
insightDataLogic(insightProps).mount()
await expectLogic(logic, () => {
logic.actions.saveInsight()
}).toFinishAllListeners()
const insightWrites = [...update.mock.calls, ...create.mock.calls].filter(([url]) =>
/\/insights\/?(\d+\/?)?$/.test(url)
)
expect(insightWrites).toHaveLength(1)
expect(insightWrites[0][1]).not.toHaveProperty('dashboards')
expect(addToDashboard.mock.calls).toEqual(expectedPlacements)
expect(groupWrites).toEqual(expectedGroupWrites)
update.mockRestore()
create.mockRestore()
addToDashboard.mockRestore()
})
test('updateInsight updates dashboards', async () => {
savedInsightsLogic().mount()
logic = insightLogic({
dashboardItemId: Insight43,
cachedInsight: {
id: 3,
},
})
logic.mount()
logic.actions.updateInsight({ name: 'updated name' })
await expectLogic(dashboardsModel).toDispatchActions(['updateDashboardInsight'])
})
test('addInsightToDashboard resolves id from short_id when id is missing', async () => {
// Simulates the race condition where the insight is added to a dashboard right after a new
// insight is saved, before loadInsight completes: it has a short_id but no numeric id yet.
const addToDashboard = jest
.spyOn(insightsApi, 'addToDashboard')
.mockResolvedValue({ id: 99, dashboard_id: MOCK_DASHBOARD_ID })
logic = insightLogic({
dashboardItemId: Insight42,
cachedInsight: {
short_id: Insight42,
// no `id` field — mirrors createEmptyInsight output
},
})
logic.mount()
await expectLogic(logic, () => {
logic.actions.addInsightToDashboard(MOCK_DASHBOARD_ID)
}).toDispatchActions(['addInsightToDashboardSuccess'])
expect(addToDashboard).toHaveBeenCalledWith(42, MOCK_DASHBOARD_ID)
addToDashboard.mockRestore()
})
test('after save as from a dashboard tile, the editor state stays on the tile insight until navigation opens the copy', async () => {
savedInsightsLogic().mount()
const insightProps: InsightLogicProps = {
dashboardItemId: Insight42,
cachedInsight: {
id: 42,
short_id: Insight42,
query: examples.InsightFunnels,
},
}
logic = insightLogic(insightProps)
logic.mount()
insightDataLogic(insightProps).mount()
await expectLogic(logic, () => {
logic.actions.saveAsConfirmation('New Insight (copy)')
})
.toDispatchActions(savedInsightsLogic(), ['loadInsights'])
.toMatchValues({
savedInsight: partial({ query: partial({ source: partial({ kind: NodeKind.FunnelsQuery }) }) }),
insight: partial({
short_id: Insight42,
query: partial({ source: partial({ kind: NodeKind.FunnelsQuery }) }),
}),
insightChanged: false,
})
await expectLogic(router)
.toDispatchActions(['push', 'locationChanged'])
.toMatchValues({
location: partial({ pathname: '/project/997/insights/12/edit' }),
})
})
describe('reacts to external changes', () => {
beforeEach(async () => {
logic = insightLogic({
dashboardItemId: Insight42,
})
logic.mount()
await expectLogic(logic).toDispatchActions(['loadInsight']).toFinishAllListeners()
})
it('reacts to rename of its own insight', async () => {
await expectLogic(logic, () => {
insightsModel.actions.renameInsightSuccess(
insightModelWith({
id: 42,
short_id: Insight42,
result: ['result 42'],
filters: API_FILTERS,
name: 'new name',
description: 'new description',
})
)
})
.toFinishAllListeners()
.toMatchValues({
insight: truth(({ name, description }) => {
return name === 'new name' && description === 'new description'
}),
})
})
it('updates query and savedInsight.query on renameInsightSuccess (display-option save)', async () => {
const updatedQuery: InsightVizNode = {
kind: NodeKind.InsightVizNode,
source: {
kind: NodeKind.TrendsQuery,
series: [],
trendsFilter: { showLegend: true },
},
}
const originalResult = logic.values.insight.result
insightsModel.actions.renameInsightSuccess(
insightModelWith({
id: 42,
short_id: Insight42,
query: updatedQuery,
result: null, // display-option PATCHes don't recompute — server returns null
})
)
// query updated, existing result preserved (not blanked by the null in the response)
expect(objectsEqual(logic.values.insight.query, updatedQuery)).toBe(true)
expect(logic.values.insight.result).toEqual(originalResult)
expect(objectsEqual(logic.values.savedInsight.query, updatedQuery)).toBe(true)
})
it('does not react to rename of a different insight', async () => {
await expectLogic(logic, () => {
insightsModel.actions.renameInsightSuccess(
insightModelWith({
id: 43,
short_id: Insight43,
result: ['result 43'],
filters: API_FILTERS,
name: 'not the insight for this logic',
})
)
})
.toFinishAllListeners()
.toMatchValues({
insight: truth(({ name }) => {
return name === 'original name'
}),
})
})
it('reacts to removal from dashboard', async () => {
await expectLogic(logic, () => {
dashboardsModel.actions.tileRemovedFromDashboard({
tile: { insight: { id: 42 } } as DashboardTile,
dashboardId: 3,
})
}).toFinishAllListeners()
expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2])
})
it('does not reacts to removal of a different tile from dashboard', async () => {
await expectLogic(logic, () => {
dashboardsModel.actions.tileRemovedFromDashboard({
tile: { insight: { id: 12 } } as DashboardTile,
dashboardId: 3,
})
}).toFinishAllListeners()
expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2, 3])
})
it('reacts to deletion of dashboard', async () => {
await expectLogic(logic, () => {
dashboardsModel.actions.deleteDashboardSuccess({ id: 3 } as DashboardType)
}).toFinishAllListeners()
expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2])
})
it('does not reacts to deletion of dashboard it is not on', async () => {
await expectLogic(logic, () => {
dashboardsModel.actions.deleteDashboardSuccess({ id: 1034 } as DashboardType)
}).toFinishAllListeners()
expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2, 3])
})
it('reacts to duplication of dashboard attaching it to new dashboard', async () => {
await expectLogic(logic, () => {
insightsModel.actions.insightsAddedToDashboard({
dashboardId: 1234,
tiles: [
{ id: 900, insightId: 0 },
{ id: 901, insightId: 1 },
{ id: 902, insightId: 42 },
],
})
}).toFinishAllListeners()
expect(logic.values.insight.dashboard_tiles).toContainEqual({ id: 902, dashboard_id: 1234 })
expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2, 3, 1234])
})
it('does not react to duplication of dashboard that did not include this insight', async () => {
await expectLogic(logic, () => {
insightsModel.actions.insightsAddedToDashboard({
dashboardId: 1234,
tiles: [
{ id: 900, insightId: 0 },
{ id: 901, insightId: 1 },
{ id: 902, insightId: 2 },
],
})
}).toFinishAllListeners()
expect(liveDashboardIds(logic.values.insight.dashboard_tiles)).toEqual([1, 2, 3])
})
})
it.each(['clean', 'draft', 'draft during refresh'])('handles an external save with a %s editor', async (state) => {
logic = insightLogic({ dashboardItemId: Insight42 })
logic.mount()
await expectLogic(logic).toFinishAllListeners()
const original = logic.values.insight
const updated = { ...original, name: 'Externally saved name' } as InsightModel
let resolveRefresh!: (value: InsightModel) => void
const refresh = new Promise<InsightModel>((resolve) => {
resolveRefresh = resolve
})
const fetchInsight = jest.spyOn(insightsApi, 'getByShortId').mockReturnValue(refresh)
if (state === 'draft') {
logic.actions.setInsightMetadataLocal({ name: 'Unsaved name' })
}
insightsModel.actions.insightSaved(Insight42)
if (state === 'draft during refresh') {
logic.actions.setInsightMetadataLocal({ name: 'Unsaved name' })
}
resolveRefresh(updated)
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.insight.name).toEqual(state === 'clean' ? 'Externally saved name' : 'Unsaved name')
if (state === 'draft') {
expect(fetchInsight).not.toHaveBeenCalled()
}
fetchInsight.mockRestore()
})
describe('setInsight name preservation', () => {
it('preserves user-edited name when loading new data for the same insight', async () => {
logic = insightLogic({ dashboardItemId: Insight42 })
logic.mount()
await expectLogic(logic).toDispatchActions(['loadInsight']).toFinishAllListeners()
// simulate user editing the name locally
logic.actions.setInsightMetadataLocal({ name: 'User Edited Name' })
await expectLogic(logic).toMatchValues({
insight: partial({ name: 'User Edited Name', short_id: Insight42 }),
})
// simulate reloading data for the same insight (e.g. query refresh) — name should be preserved
logic.actions.setInsight(
{ ...logic.values.insight, name: '', short_id: Insight42 },
{ fromPersistentApi: false, overrideQuery: false }
)
await expectLogic(logic).toMatchValues({
insight: partial({ name: 'User Edited Name' }),
})
})
it('does not preserve name when switching to a new insight', async () => {
logic = insightLogic({ dashboardItemId: Insight42 })
logic.mount()
await expectLogic(logic).toDispatchActions(['loadInsight']).toFinishAllListeners()
// confirm the loaded insight has a name
await expectLogic(logic).toMatchValues({
insight: partial({ name: 'original name', short_id: Insight42 }),
})
// simulate switching to a brand new insight (no short_id)
logic.actions.setInsight(
{ ...createEmptyInsight('new'), query: logic.values.insight.query },
{ fromPersistentApi: false, overrideQuery: true }
)
await expectLogic(logic).toMatchValues({
insight: partial({ name: undefined }),
})
})
})
describe('saving query based insights', () => {
beforeEach(async () => {
const insightProps: InsightLogicProps = { dashboardItemId: 'new' }
logic = insightLogic(insightProps)
logic.mount()
insightDataLogic(insightProps).mount()
})
it('sends query when saving', async () => {
jest.spyOn(api, 'create')
await expectLogic(logic, () => {
logic.actions.setInsight(
{
query: {
kind: NodeKind.DataTableNode,
source: { kind: NodeKind.EventsQuery, select: ['*'] },
} as DataTableNode,
},
{ overrideQuery: true }
)
logic.actions.saveInsight()
})
const mockCreateCalls = (api.create as jest.Mock).mock.calls
expect(mockCreateCalls).toEqual([
[
`api/projects/${MOCK_TEAM_ID}/insights`,
expect.objectContaining({
derived_name: '* from events',
query: {
kind: 'DataTableNode',
source: { kind: 'EventsQuery', select: ['*'] },
},
saved: true,
}),
expect.objectContaining({
data: expect.objectContaining({
derived_name: '* from events',
query: {
kind: 'DataTableNode',
source: { kind: 'EventsQuery', select: ['*'] },
},
saved: true,
}),
}),
],
])
})
})
describe('PostHog AI suggestions', () => {
const suggestedQuery: InsightVizNode = {
kind: NodeKind.InsightVizNode,
source: {
kind: NodeKind.TrendsQuery,
series: [{ kind: NodeKind.EventsNode, event: '$pageview', math: BaseMathType.TotalCount }],
},
}
let vizLogic: ReturnType<typeof insightVizDataLogic.build>
const mountInsight = async (dashboardItemId: InsightShortId | 'new'): Promise<void> => {
const insightProps: InsightLogicProps = { dashboardItemId }
logic = insightLogic(insightProps)
logic.mount()
insightDataLogic(insightProps).mount()
vizLogic = insightVizDataLogic(insightProps)
vizLogic.mount()
// A saved insight loads asynchronously and re-syncs the query when it arrives, which
// would land on top of a suggestion applied before then.
await expectLogic(logic).toFinishAllListeners()
}
const suggest = (): void => {
logic.actions.handleInsightSuggested(suggestedQuery)
vizLogic.actions.setQuery(suggestedQuery)
}
it.each([
['an unsaved', 'new' as const],
['a saved', Insight42],
])('keeping the changes on %s insight ends the review and holds on to the query', async (_, insightId) => {
await mountInsight(insightId)
suggest()
await expectLogic(logic, () => {
logic.actions.onKeepSuggestedInsight()
}).toMatchValues({
previousQuery: null,
suggestedQuery: null,
query: suggestedQuery,
})
})
it('an edit made after the suggestion keeps it, so a reject cannot revert the edit', async () => {
await mountInsight('new')
suggest()
await expectLogic(logic, () => {
vizLogic.actions.updateQuerySource({ filterTestAccounts: true })
}).toMatchValues({
previousQuery: null,
suggestedQuery: null,
})
})
it('rejecting the suggestion restores the previous query and leaves it available to reapply', async () => {
await mountInsight('new')
const queryBeforeSuggestion = logic.values.query
suggest()
await expectLogic(logic, () => {
logic.actions.onRejectSuggestedInsight()
}).toMatchValues({
previousQuery: null,
suggestedQuery,
query: queryBeforeSuggestion,
})
})
})
describe('confirmDeleteInsight', () => {
beforeEach(async () => {
const insightProps: InsightLogicProps = { dashboardItemId: Insight42 }
logic = insightLogic(insightProps)
logic.mount()
await expectLogic(logic)
.toFinishAllListeners()
.toMatchValues({
insight: partial({ id: 42 }),
})
})
it.each([
{ scenario: 'with dashboardId', dashboardId: 5 },
{ scenario: 'without dashboardId', dashboardId: null },
])('$scenario deletes via API then navigates', async ({ dashboardId }) => {
jest.spyOn(api, 'update')
logic.actions.confirmDeleteInsight(dashboardId)
await expectLogic(logic).toFinishAllListeners()
expect(api.update).toHaveBeenCalledWith(
expect.stringContaining('/insights/42'),
expect.objectContaining({ deleted: true })
)
expect((api.update as jest.Mock).mock.calls[0][1]).not.toHaveProperty('dashboards')
const expectedUrl = dashboardId ? urls.dashboard(dashboardId) : urls.savedInsights()
await expectLogic(router).toDispatchActions([router.actionCreators.push(expectedUrl)])
})
it('undo puts the insight back on its dashboards, except one deleted in the meantime', async () => {
const info = jest.spyOn(lemonToast, 'info')
const addToDashboard = jest
.spyOn(insightsApi, 'addToDashboard')
.mockImplementation(async (_insightId, dashboardId) => ({ id: 99, dashboard_id: dashboardId }))
dashboardsModel.actions.deleteDashboardSuccess({ id: 3 } as DashboardType)
logic.actions.confirmDeleteInsight(null)
await expectLogic(logic).toFinishAllListeners()
await info.mock.calls[0][1]?.button?.action()
expect(addToDashboard.mock.calls).toEqual([
[42, 1],
[42, 2],
])
addToDashboard.mockRestore()
})
it('restores insight on undo from dashboard', async () => {
logic.actions.confirmDeleteInsight(5)
await expectLogic(logic).toFinishAllListeners()
// Simulate undo — the callback with undo=true should restore the insight
await expectLogic(dashboardsModel, () => {
dashboardsModel
.findMounted()
?.actions.updateDashboardInsight({ ...(logic.values.insight as InsightModel), deleted: false }, [5])
}).toDispatchActions([
(action: any) =>
action.type === dashboardsModel.actionTypes.updateDashboardInsight &&
action.payload.insight.deleted === false,
])
})
})
describe('duplicateInsight', () => {
beforeEach(async () => {
const insightProps: InsightLogicProps = { dashboardItemId: Insight42 }
logic = insightLogic(insightProps)
logic.mount()
await expectLogic(logic)
.toFinishAllListeners()
.toMatchValues({
insight: partial({ id: 42 }),
})
})
it('fetches clean insight before duplicating', async () => {
jest.spyOn(api, 'create')
const addToDashboard = jest
.spyOn(insightsApi, 'addToDashboard')
.mockImplementation(async (_insightId, dashboardId) => ({ id: 99, dashboard_id: dashboardId }))
logic.actions.duplicateInsight(logic.values.insight as InsightModel, true)
await expectLogic(logic).toFinishAllListeners()
// The POST body should contain the clean insight fetched via getByShortId,
// not the one passed in (which may have dashboard filter overrides)
expect(api.create).toHaveBeenCalledWith(
expect.stringContaining('/insights'),
expect.objectContaining({ name: 'original name (copy)' }),
expect.anything()
)
expect(api.create).not.toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ dashboards: expect.anything() }),
expect.anything()
)
expect(addToDashboard.mock.calls).toEqual([
[12, 1],
[12, 2],
[12, 3],
])
addToDashboard.mockRestore()
})
it('falls back to original insight when fetch fails', async () => {
jest.spyOn(api, 'create')
const insightWithBadShortId = {
...(logic.values.insight as InsightModel),
short_id: '500' as InsightShortId,
name: 'fallback name',
}
logic.actions.duplicateInsight(insightWithBadShortId, false)
await expectLogic(logic).toFinishAllListeners()
expect(api.create).toHaveBeenCalledWith(
expect.stringContaining('/insights'),
expect.objectContaining({ name: 'fallback name (copy)' }),
expect.anything()
)
})
it('with redirectToInsight=true navigates to edit URL', async () => {
// POST mock returns short_id: Insight12 — listen on router before dispatching
await expectLogic(router, () => {
logic.actions.duplicateInsight(logic.values.insight as InsightModel, true)
}).toDispatchActions([router.actionCreators.push(urls.insightEdit(Insight12))])
})
it('with redirectToInsight=false does not navigate', async () => {
await expectLogic(logic, () => {
logic.actions.duplicateInsight(logic.values.insight as InsightModel, false)
}).toFinishAllListeners()
await expectLogic(router).toNotHaveDispatchedActions(['push'])
})
it('marks the insight as duplicating until the request settles', async () => {
await expectLogic(logic, () => {
logic.actions.duplicateInsight(logic.values.insight as InsightModel, true)
})
.toMatchValues({ insightDuplicating: true })
.toFinishAllListeners()
.toMatchValues({ insightDuplicating: false })
})
// Catching the rejection skips the gate `initKea` applies to loader failures, so the
// listener has to reapply it: a validation error is the app's own bug and stays
// reportable, while an access-denied 403 the AccessDenied scene already handles would
// file an issue sharing its stack with every other ApiError, burying real crashes.
it.each([
['a validation error', 400, { detail: 'Insight limit reached' }, 1],
[
'a failure the app recovers from',
403,
{ detail: 'You do not have permission', code: 'permission_denied' },
0,
],
])(
'toasts %s rather than doing nothing, and reports it only if it is worth filing',
async (_, status, body, timesReported) => {
useMocks({
post: {
'/api/environments/:team_id/insights/': () => [status, body],
},
})
jest.spyOn(lemonToast, 'error')
jest.spyOn(posthog, 'captureException')
await expectLogic(logic, () => {
logic.actions.duplicateInsight(logic.values.insight as InsightModel, true)
})
.toFinishAllListeners()
.toMatchValues({ insightDuplicating: false })
expect(lemonToast.error).toHaveBeenCalledWith(body.detail)
expect(posthog.captureException).toHaveBeenCalledTimes(timesReported)
await expectLogic(router).toNotHaveDispatchedActions(['push'])
}
)
})
describe('hasOverrides', () => {
it.each([
['no overrides present', { filtersOverride: null, variablesOverride: null }, false],
['filtersOverride has a date_from', { filtersOverride: { date_from: '-7d' } }, true],
[
'variablesOverride is non-empty',
{ variablesOverride: { var1: { code_name: 'var1', variableId: '123', value: 'x' } } },
true,
],
['filtersOverride is an empty object', { filtersOverride: {} }, false],
['tileFiltersOverride has a date_from', { tileFiltersOverride: { date_from: '-30d' } }, true],
])('is %s → %s', (_label, propsOverride, expected) => {
logic = insightLogic({
dashboardItemId: Insight42,
cachedInsight: { ...partialInsight42, query: API_QUERY },
...propsOverride,
})
logic.mount()
expect(logic.values.hasOverrides).toBe(expected)
})
})
describe('loadInsight refresh mode', () => {
// Overridden queries get their own cache key, which nothing warms — a cache-only-ish
// `async` read yields `result: null` and the scene shows "Chart data didn't load".
const seenRefreshParams: (string | null)[] = []
beforeEach(() => {
seenRefreshParams.length = 0
useMocks({
get: {
'/api/environments/:team_id/insights/': ({ request }) => {
const url = new URL(request.url)
seenRefreshParams.push(url.searchParams.get('refresh'))
return [
200,
{
results: [
{
id: 42,
short_id: Insight42,
result: ['result from api'],
filters: API_FILTERS,
name: 'original name',
},
],
},
]
},
},
})
})
it('uses async without overrides', async () => {
logic = insightLogic({ dashboardItemId: Insight42 })
logic.mount()
await expectLogic(logic).toDispatchActions(['loadInsightSuccess'])
expect(seenRefreshParams).toEqual(['async'])
})
it('blocks on a cache miss when overrides are present', async () => {
logic = insightLogic({
dashboardItemId: Insight42,
dashboardId: 33,
filtersOverride: { date_from: '-14d' },
})
logic.mount()
await expectLogic(logic).toDispatchActions(['loadInsightSuccess'])
expect(seenRefreshParams).toEqual(['async_except_on_cache_miss'])
})
it('treats empty overrides as no overrides', async () => {
logic = insightLogic({
dashboardItemId: Insight42,
dashboardId: 33,
filtersOverride: {},
})
logic.mount()
await expectLogic(logic).toDispatchActions(['loadInsightSuccess'])
expect(seenRefreshParams).toEqual(['async'])
})
})
describe('insightMissing', () => {
// A notebook cell binds a saved insight by short id. When that insight is gone, the API
// returns no results and the loader throws — the cell needs a flag it can turn into a
// "not found" screen instead of silently rendering a blank default query.
it('is set when the insight cannot be found', async () => {
useMocks({
get: {
'/api/environments/:team_id/insights/': () => [200, { results: [] }],
},
})
logic = insightLogic({ dashboardItemId: Insight42 })
logic.mount()
await expectLogic(logic).toDispatchActions(['loadInsightFailure'])
expect(logic.values.insightMissing).toBe(true)
})
})
describe('editingDisabledReason', () => {
it.each([
['overrides present', { filtersOverride: { date_from: '-7d' } }, 'Discard overrides to edit the insight.'],
['no overrides', { filtersOverride: null }, null],
])('returns correct value when %s', (_label, propsOverride, expected) => {
logic = insightLogic({
dashboardItemId: Insight42,
cachedInsight: { ...partialInsight42, query: API_QUERY },
...propsOverride,
})
logic.mount()
expect(logic.values.editingDisabledReason).toBe(expected)
})
})
describe('canEditInsight', () => {
it.each([
['editor access level', AccessControlLevel.Editor, true],
['viewer access level', AccessControlLevel.Viewer, false],
])('is correct with %s', (_label, accessLevel, expected) => {
logic = insightLogic({
dashboardItemId: Insight42,
cachedInsight: {
...partialInsight42,
query: API_QUERY,
user_access_level: accessLevel,
},
})
logic.mount()
expect(logic.values.canEditInsight).toBe(expected)
})
})
describe('setInsightMetadataSuccess on savedInsight', () => {
it('syncs name, description, and tags to savedInsight after metadata save', async () => {
const insightProps: InsightLogicProps = {
dashboardItemId: Insight43,
cachedInsight: {
...partialInsight43,
query: API_QUERY,
name: 'Original 43',
description: 'Original description',
tags: [],
},
}
logic = insightLogic(insightProps)
logic.mount()
await expectLogic(logic).toMatchValues({
savedInsight: partial({ name: 'Original 43', description: 'Original description', tags: [] }),
insightChanged: false,
})
await expectLogic(logic, () => {
logic.actions.setInsightMetadataLocal({
name: 'Foobar 43',
description: 'Lorem ipsum.',
tags: ['good'],
})
}).toMatchValues({
insight: partial({ name: 'Foobar 43', description: 'Lorem ipsum.', tags: ['good'] }),
savedInsight: partial({ name: 'Original 43', description: 'Original description', tags: [] }),
insightChanged: true,
})
// The PATCH mock for id=43 returns name: 'Foobar 43', description: 'Lorem ipsum.', tags: ['good']
await expectLogic(logic, () => {
logic.actions.setInsightMetadata({ name: 'Foobar 43', description: 'Lorem ipsum.', tags: ['good'] })
})
.toDispatchActions([tagsModel.actionTypes.loadTags, 'setInsightMetadataSuccess'])
.toMatchValues({
savedInsight: partial({ name: 'Foobar 43', description: 'Lorem ipsum.', tags: ['good'] }),
insightChanged: false,
})
})
it('syncs favorited to savedInsight on metadata save', async () => {
useMocks({
patch: {
'/api/environments/:team_id/insights/:id': async ({ request }) => {
const payload = (await request.json()) as Record<string, any>
return [
200,
{
...partialInsight43,
name: 'Foobar 43',
description: 'Lorem ipsum.',
tags: ['good'],
...payload,
},
]
},
},
})
const insightProps: InsightLogicProps = {
dashboardItemId: Insight43,
cachedInsight: {
...partialInsight43,
query: API_QUERY,
name: 'Foobar 43',
description: 'Lorem ipsum.',
tags: ['good'],
favorited: false,
},
}
logic = insightLogic(insightProps)
logic.mount()
await expectLogic(logic).toMatchValues({
savedInsight: partial({ favorited: false }),
})
await expectLogic(logic, () => {
logic.actions.setInsightMetadata({ favorited: true })
})
.toDispatchActions(['setInsightMetadataSuccess'])
.toNotHaveDispatchedActions([tagsModel.actionTypes.loadTags])
.toMatchValues({
savedInsight: partial({ favorited: true }),
})
})
})
describe('updateDashboardInsight query merge', () => {
const canonicalQuery = {
kind: NodeKind.InsightVizNode,
source: {
kind: NodeKind.TrendsQuery,
series: [{ kind: NodeKind.EventsNode, event: '$pageview', math: BaseMathType.TotalCount }],
dateRange: { date_from: 'all' },
},
}
const dashboardOverriddenQuery = {
...canonicalQuery,
source: {
...canonicalQuery.source,
dateRange: { date_from: '-14d' },
},
}
beforeEach(() => {
logic = insightLogic({
dashboardItemId: Insight42,
dashboardId: MOCK_DASHBOARD_ID,
cachedInsight: insightModelWith({ query: canonicalQuery }),
})
logic.mount()
})
it('does not overwrite the canonical query on a dashboard-scoped refresh', async () => {
dashboardsModel.actions.updateDashboardInsight(
insightModelWith({
query: dashboardOverriddenQuery,
dashboard_tiles: [{ dashboard_id: MOCK_DASHBOARD_ID }],
}),
undefined,
MOCK_DASHBOARD_ID
)
await expectLogic(logic).toMatchValues({ insight: partial({ query: canonicalQuery }) })
})
it('applies the query from a non-scoped update', async () => {
dashboardsModel.actions.updateDashboardInsight(
insightModelWith({
query: dashboardOverriddenQuery,
dashboard_tiles: [{ dashboard_id: MOCK_DASHBOARD_ID }],
})
)
await expectLogic(logic).toMatchValues({ insight: partial({ query: dashboardOverriddenQuery }) })
})
})
})