: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_TEAM_ID } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { dashboardsModel } from '~/models/dashboardsModel'
import { initKeaTests } from '~/test/init'
import { InsightModel, SavedInsightsTabs } from '~/types'
import { DeleteDashboardForm, deleteDashboardLogic } from 'products/dashboards/frontend/deleteDashboardLogic'
import { DuplicateDashboardForm, duplicateDashboardLogic } from 'products/dashboards/frontend/duplicateDashboardLogic'
import {
INSIGHTS_PER_PAGE,
InsightsResult,
SavedInsightFilters,
cleanFilters,
hasNarrowingFilters,
savedInsightsLogic,
} from './savedInsightsLogic'
jest.spyOn(api, 'create')
const blankScene = (): any => ({ scene: { component: () => null, logic: null } })
const scenes: any = { [Scene.SavedInsights]: blankScene }
const createInsight = (id: number, string = 'hi'): InsightModel =>
({
id: id || 1,
name: `${string} ${id || 1}`,
short_id: `ii${id || 1}`,
order: 0,
layouts: [],
last_refresh: 'now',
refreshing: false,
created_by: null,
is_sample: false,
updated_at: 'now',
result: {},
color: null,
created_at: 'now',
dashboard: null,
deleted: false,
saved: true,
query: {},
}) as any as InsightModel
const createSavedInsights = (string = 'hello', offset: number): InsightsResult => ({
count: 3,
results: [createInsight(1, string), createInsight(2, string), createInsight(3, string)].slice(offset),
offset: 0,
})
describe('savedInsightsLogic', () => {
let logic: ReturnType<typeof savedInsightsLogic.build>
beforeEach(() => {
useMocks({
get: {
'/api/environments/:team_id/insights/': ({ request }) => {
const url = new URL(request.url)
return [
200,
createSavedInsights(
url.searchParams.get('search') ?? '',
parseInt(url.searchParams.get('offset') ?? '0')
),
]
},
'/api/environments/:team_id/insights/42': createInsight(42),
'/api/environments/:team_id/insights/123': createInsight(123),
},
post: {
'/api/environments/:team_id/insights/': () => [200, createInsight(42)],
},
})
initKeaTests()
featureFlagLogic.actions.setFeatureFlags([], {})
sceneLogic({ scenes }).mount()
router.actions.push(urls.project(MOCK_TEAM_ID, urls.savedInsights()))
logic = savedInsightsLogic({ tabId: '1' })
logic.mount()
})
beforeEach(async () => {
// wait for the initial load, and assure it fetches results after mount
await expectLogic(logic).toDispatchActions(['setSavedInsightsFilters', 'loadInsights', 'loadInsightsSuccess'])
})
describe('default tab', () => {
const savedInsightsUrl = urls.project(MOCK_TEAM_ID, urls.savedInsights())
it.each([
['missing flag', undefined, SavedInsightsTabs.All],
['test variant', 'test', SavedInsightsTabs.Home],
['boolean enabled', true, SavedInsightsTabs.Home],
['control variant', 'control', SavedInsightsTabs.All],
['boolean disabled', false, SavedInsightsTabs.All],
])('uses the correct default for %s', async (_, flagValue, expectedTab) => {
if (flagValue !== undefined) {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]: flagValue,
})
}
router.actions.push(savedInsightsUrl)
await expectLogic(logic)
.toFinishAllListeners()
.toMatchValues({
filters: partial({ tab: expectedTab }),
})
})
it('keeps tab-less filtered links on All insights when Home is enabled', async () => {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]: 'test',
})
router.actions.push(savedInsightsUrl, { search: 'revenue' })
await expectLogic(logic)
.toFinishAllListeners()
.toMatchValues({
filters: partial({ tab: SavedInsightsTabs.All, search: 'revenue' }),
})
expect(router.values.searchParams).toEqual({ search: 'revenue' })
})
it('preserves an explicit tab when Home is enabled', async () => {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]: 'test',
})
router.actions.push(savedInsightsUrl, { tab: SavedInsightsTabs.Yours })
await expectLogic(logic)
.toFinishAllListeners()
.toMatchValues({
filters: partial({ tab: SavedInsightsTabs.Yours }),
})
})
it('falls back to All insights when a Home link opens without the flag', async () => {
router.actions.push(savedInsightsUrl, { tab: SavedInsightsTabs.Home })
await expectLogic(logic)
.toFinishAllListeners()
.toMatchValues({
filters: partial({ tab: SavedInsightsTabs.All }),
})
expect(router.values.searchParams).toEqual({})
})
it('keeps All insights explicit when a flagged user selects it', async () => {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.PRODUCT_ANALYTICS_HOME_TAB]: 'test',
})
router.actions.push(savedInsightsUrl)
await expectLogic(logic).toFinishAllListeners()
logic.actions.setSavedInsightsFilters({ tab: SavedInsightsTabs.All })
await expectLogic(logic)
.toFinishAllListeners()
.toMatchValues({
filters: partial({ tab: SavedInsightsTabs.All }),
})
expect(router.values.searchParams).toEqual({ tab: SavedInsightsTabs.All })
})
})
it('always asks the API to exclude auto-generated feature flag insights', () => {
expect(logic.values.paramsFromFilters).toMatchObject({ hide_feature_flag_insights: true })
})
it('can filter the insights', async () => {
// makes a search query
logic.actions.setSavedInsightsFilters({ search: 'hello' })
await expectLogic(logic)
.toDispatchActions(['loadInsights', 'loadInsightsSuccess'])
.toMatchValues({
filters: partial({ search: 'hello' }),
insights: {
results: partial([partial({ name: 'hello 1' })]),
count: 3,
offset: 0,
filters: partial({ search: 'hello' }),
},
})
// will not search for a second time
logic.actions.setSavedInsightsFilters({ search: 'hello' })
await expectLogic(logic)
.toNotHaveDispatchedActions(['loadInsights', 'loadInsightsSuccess'])
.toMatchValues({
filters: partial({ search: 'hello' }),
insights: {
results: partial([partial({ name: 'hello 1' })]),
count: 3,
offset: 0,
filters: partial({ search: 'hello' }),
},
})
// insights.filters always has the loaded filters
logic.actions.setSavedInsightsFilters({ search: 'hello again' })
await expectLogic(logic)
.toDispatchActions(['loadInsights'])
.toMatchValues({
filters: partial({ search: 'hello again' }),
insights: {
results: partial([partial({ name: 'hello 1' })]),
count: 3,
offset: 0,
filters: partial({ search: 'hello' }),
},
})
.toDispatchActions(['loadInsightsSuccess'])
.toMatchValues({
filters: partial({ search: 'hello again' }),
insights: {
results: partial([partial({ name: 'hello again 1' })]),
count: 3,
offset: 0,
filters: partial({ search: 'hello again' }),
},
})
})
it('resets the page on filter change', async () => {
logic.actions.setSavedInsightsFilters({ page: 2 })
await expectLogic(logic)
.toDispatchActions(['loadInsights', 'loadInsightsSuccess'])
.toMatchValues({
filters: partial({ page: 2, search: '' }),
insights: {
results: [],
count: 3,
offset: INSIGHTS_PER_PAGE,
filters: partial({ page: 2, search: '' }),
},
})
logic.actions.setSavedInsightsFilters({ search: 'hello' })
await expectLogic(logic)
.toDispatchActions(['loadInsights', 'loadInsightsSuccess'])
.toMatchValues({
filters: partial({ page: 1, search: 'hello' }),
insights: {
results: partial([partial({ name: 'hello 1' })]),
count: 3,
offset: 0,
filters: partial({ page: 1, search: 'hello' }),
},
})
})
it('persists the filter in the url', async () => {
logic.actions.setSavedInsightsFilters({ search: 'hello' })
await expectLogic(logic)
.toDispatchActions(['loadInsightsSuccess'])
.toMatchValues({ filters: partial({ search: 'hello' }) })
.toMatchValues(router, { searchParams: { search: 'hello' } })
router.actions.push(router.values.location.pathname, { search: 'hoi' })
await expectLogic(logic)
.toDispatchActions(['loadInsightsSuccess'])
.toMatchValues({ filters: partial({ search: 'hoi' }) })
.toMatchValues(router, { searchParams: { search: 'hoi' } })
})
it('makes a direct ID query if searching for a number', async () => {
logic.actions.setSavedInsightsFilters({ search: '123' })
await expectLogic(logic)
.toDispatchActions(['loadInsightsSuccess'])
.toMatchValues({
insights: partial({
filters: partial({ search: '123' }),
results: [partial({ id: 123 }), partial({ id: 1 }), partial({ id: 2 }), partial({ id: 3 })],
}),
})
})
it('carries per-row search_match_type through to the results', async () => {
useMocks({
get: {
'/api/environments/:team_id/insights/': () => {
const base = createSavedInsights('hello', 0)
return [
200,
{
...base,
results: base.results.map((r, i) => ({
...r,
search_match_type: i === 0 ? 'exact' : 'similar',
})),
},
]
},
},
})
logic.actions.setSavedInsightsFilters({ search: 'hello' })
await expectLogic(logic)
.toDispatchActions(['loadInsights', 'loadInsightsSuccess'])
.toMatchValues({
insights: partial({
results: partial([
partial({ name: 'hello 1', search_match_type: 'exact' }),
partial({ name: 'hello 2', search_match_type: 'similar' }),
]),
}),
})
})
it('can duplicate and does not use derived name for name', async () => {
const sourceInsight = createInsight(123, 'hello')
sourceInsight.name = ''
sourceInsight.derived_name = 'should be copied'
await logic.asyncActions.duplicateInsight(sourceInsight)
// Duplication runs through api.insights.create, which still builds the environments path.
expect(api.create).toHaveBeenCalledWith(
`api/projects/${MOCK_TEAM_ID}/insights`,
expect.objectContaining({ name: '' }),
expect.objectContaining({})
)
})
it('can duplicate using name', async () => {
const sourceInsight = createInsight(123, 'hello')
sourceInsight.name = 'should be copied'
sourceInsight.derived_name = ''
await logic.asyncActions.duplicateInsight(sourceInsight)
// Duplication runs through api.insights.create, which still builds the environments path.
expect(api.create).toHaveBeenCalledWith(
`api/projects/${MOCK_TEAM_ID}/insights`,
expect.objectContaining({ name: 'should be copied (copy)' }),
expect.objectContaining({})
)
})
it('flags a failed load so the list can show an error instead of an empty state', async () => {
useMocks({
get: {
'/api/environments/:team_id/insights/': () => [500, { detail: 'boom' }],
},
})
logic.actions.loadInsights(false)
await expectLogic(logic)
.toDispatchActions(['loadInsights', 'loadInsightsFailure'])
.toMatchValues({ insightsLoadFailed: true })
// A later successful load clears the flag so a recovered list drops the error state
useMocks({
get: {
'/api/environments/:team_id/insights/': () => [200, createSavedInsights('recovered', 0)],
},
})
logic.actions.loadInsights(false)
await expectLogic(logic)
.toDispatchActions(['loadInsights', 'loadInsightsSuccess'])
.toMatchValues({ insightsLoadFailed: false })
})
it('discards stale API responses when a newer request is in flight', async () => {
const pendingRequests: Array<{
resolve: (value: [number, any]) => void
search: string
}> = []
let onRequestArrived: (() => void) | null = null
const waitForNextRequest = (): Promise<void> =>
new Promise<void>((r) => {
onRequestArrived = r
})
useMocks({
get: {
'/api/environments/:team_id/insights/': ({ request }) => {
const search = new URL(request.url).searchParams.get('search') ?? ''
return new Promise<[number, any]>((resolve) => {
pendingRequests.push({ resolve, search })
onRequestArrived?.()
onRequestArrived = null
})
},
},
})
// Fire two loads — both go in-flight concurrently
const req1 = waitForNextRequest()
logic.actions.loadInsights(false)
await req1
const req2 = waitForNextRequest()
logic.actions.loadInsights(false)
await req2
expect(pendingRequests).toHaveLength(2)
// Resolve out of order: second (fresh) first, then first (stale)
pendingRequests[1].resolve([200, createSavedInsights('fresh', 0)])
pendingRequests[0].resolve([200, createSavedInsights('stale', 0)])
await expectLogic(logic).toFinishAllListeners()
// The stale response that arrived last must NOT overwrite the fresh one
await expectLogic(logic).toMatchValues({
insights: partial({
results: partial([partial({ name: 'fresh 1' })]),
}),
})
})
describe('reacts to external updates', () => {
it('loads insights when a dashboard is duplicated', async () => {
await expectLogic(logic, () => {
duplicateDashboardLogic.actions.submitDuplicateDashboardSuccess({
duplicateTiles: true,
} as DuplicateDashboardForm)
}).toDispatchActions(['loadInsights'])
})
it('loads insights when a dashboard is deleted', async () => {
await expectLogic(logic, () => {
deleteDashboardLogic.actions.submitDeleteDashboardSuccess({
deleteInsights: true,
} as DeleteDashboardForm)
}).toDispatchActions(['loadInsights'])
})
it('updates the list when an insight is changed', async () => {
await expectLogic(logic, () => {
dashboardsModel.actions.updateDashboardInsight(createInsight(1, 'a new name'))
}).toDispatchActions(['updateInsight'])
})
it('adds to the list when a new insight is reported as changed', async () => {
await expectLogic(logic, () => {
dashboardsModel.actions.updateDashboardInsight(createInsight(100, 'a new insight'))
}).toDispatchActions(['addInsight'])
})
})
describe('draft insight row', () => {
const draftKey = `draft-query-${MOCK_TEAM_ID}`
const draft = {
query: { kind: 'InsightVizNode', source: { kind: 'TrendsQuery', series: [] } },
timestamp: 1721000000000,
}
afterEach(() => {
localStorage.removeItem(draftKey)
})
it('loads a stored draft into the draft row', async () => {
localStorage.setItem(draftKey, JSON.stringify(draft))
logic.actions.loadDraftQuery()
await expectLogic(logic).toMatchValues({
draftQuery: draft,
draftInsightRow: partial({ id: -1, query: draft.query }),
})
})
it.each([
['unparseable JSON', 'not json'],
['a non-numeric timestamp', JSON.stringify({ query: { kind: 'TrendsQuery' }, timestamp: 'yesterday' })],
['a query without a kind', JSON.stringify({ query: {}, timestamp: 1721000000000 })],
])('drops a malformed draft (%s) instead of surfacing it', async (_label, storedValue) => {
localStorage.setItem(draftKey, storedValue)
logic.actions.loadDraftQuery()
await expectLogic(logic).toMatchValues({ draftQuery: null, draftInsightRow: null })
expect(localStorage.getItem(draftKey)).toBeNull()
})
it('hides the draft row while narrowing filters are active', async () => {
localStorage.setItem(draftKey, JSON.stringify(draft))
logic.actions.loadDraftQuery()
logic.actions.setSavedInsightsFilters({ search: 'revenue' })
await expectLogic(logic).toMatchValues({ draftInsightRow: null })
logic.actions.setSavedInsightsFilters({ search: '' })
await expectLogic(logic).toMatchValues({ draftInsightRow: partial({ id: -1 }) })
// Clearing the tag filter sends an empty array, which must read as "no filter"
logic.actions.setSavedInsightsFilters({ tags: ['marketing'] })
await expectLogic(logic).toMatchValues({ draftInsightRow: null })
logic.actions.setSavedInsightsFilters({ tags: [] })
await expectLogic(logic).toMatchValues({ draftInsightRow: partial({ id: -1 }) })
})
it.each<[string, Partial<SavedInsightFilters>]>([
['the tab', { tab: SavedInsightsTabs.Yours }],
['the page', { page: 2 }],
['the sort order', { order: 'name' }],
['a cleared tag filter', { tags: [] }],
['a cleared created-by filter', { createdBy: [] }],
])('does not count %s as a narrowing filter', (_label, overrides) => {
expect(hasNarrowingFilters(cleanFilters(overrides))).toBe(false)
})
it.each<[string, Partial<SavedInsightFilters>]>([
['a search', { search: 'revenue' }],
['an insight type', { insightType: 'TRENDS' }],
['tags', { tags: ['marketing'] }],
['created by', { createdBy: [1] }],
['favorites', { favorited: true }],
['a date range', { dateFrom: '-7d' }],
['a dashboard', { dashboardId: 5 }],
])('counts %s as a narrowing filter', (_label, overrides) => {
expect(hasNarrowingFilters(cleanFilters(overrides))).toBe(true)
})
it('discarding a draft clears localStorage so it does not come back', async () => {
localStorage.setItem(draftKey, JSON.stringify(draft))
logic.actions.loadDraftQuery()
logic.actions.discardDraftQuery()
await expectLogic(logic).toMatchValues({ draftQuery: null, draftInsightRow: null })
await expectLogic(eventUsageLogic).toDispatchActions(['reportInsightDraftDiscarded'])
expect(localStorage.getItem(draftKey)).toBeNull()
})
})
})