: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 { LemonDialog } from '@posthog/lemon-ui'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { dataWarehouseViewsLogic } from 'scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { lineageDataLogic } from 'products/data_modeling/frontend/lineage/lineageDataLogic'
import { PAGE_SIZE, viewsTabLogic } from './viewsTabLogic'
function buildView(id: string, isMaterialized: boolean, status?: string): Record<string, unknown> {
return {
id,
name: id,
columns: [],
is_materialized: isMaterialized,
status,
created_at: '2024-01-01T00:00:00Z',
}
}
describe('viewsTabLogic', () => {
let logic: ReturnType<typeof viewsTabLogic.build>
let runHistoryRequests: string[]
beforeEach(async () => {
runHistoryRequests = []
const views = [
...Array.from({ length: PAGE_SIZE + 1 }, (_, i) =>
buildView(`mat-${i}`, true, i === 1 ? 'Running' : i === 10 ? 'Failed' : 'Completed')
),
buildView('plain-a', false),
buildView('plain-b', false),
]
useMocks({
get: {
'/api/projects/:team_id/warehouse_saved_queries/': { count: views.length, results: views },
'/api/environments/:team_id/data_modeling_nodes/': { count: 0, results: [] },
'/api/environments/:team_id/data_modeling_edges/': { count: 0, results: [] },
'/api/environments/:team_id/warehouse_saved_queries/:id/run_history/': (req) => {
runHistoryRequests.push(String(req.params.id))
return [200, { run_history: [] }]
},
},
post: { '/api/environments/:team_id/query/': { tables: {} } },
delete: { '/api/environments/:team_id/warehouse_saved_queries/:id/': [204, null] },
})
initKeaTests()
logic = viewsTabLogic()
logic.mount()
await expectLogic(logic).toFinishAllListeners()
})
it('loads run history only for the materialized views on the visible page', () => {
expect(logic.values.visibleViews).toHaveLength(PAGE_SIZE)
expect(runHistoryRequests).toHaveLength(PAGE_SIZE)
expect(runHistoryRequests.every((id) => id.startsWith('mat-'))).toBe(true)
})
it('narrows the list by type and resets to the first page', async () => {
logic.actions.setPage(2)
expect(logic.values.currentPage).toEqual(2)
logic.actions.setTypeFilter('view')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.currentPage).toEqual(1)
expect(logic.values.filteredViews.map((view) => view.id)).toEqual(['plain-a', 'plain-b'])
})
it('search, status, and type filters compose', async () => {
logic.actions.setTypeFilter('materialized')
logic.actions.setSearchTerm('mat-1 status:failed')
await expectLogic(logic).toFinishAllListeners()
expect(logic.values.filteredViews.map((view) => view.id)).toEqual(['mat-10'])
})
it.each([
['a materialize', 'plain-a', true],
['an unmaterialize', 'mat-0', false],
])('shows the new materialization after %s suggestion is accepted', async (_kind, viewId, isMaterialized) => {
useMocks({
get: {
'/api/projects/:team_id/warehouse_saved_queries/': {
count: 1,
results: [buildView(viewId, isMaterialized, isMaterialized ? 'Completed' : undefined)],
},
},
})
logic.actions.suggestionAccepted(viewId, isMaterialized)
await expectLogic(dataWarehouseViewsLogic).toFinishAllListeners()
logic.actions.setTypeFilter(isMaterialized ? 'materialized' : 'view')
expect(logic.values.filteredViews.map((view) => view.id)).toEqual([viewId])
})
it.each([
['a materialize', 'view' as const, false],
['an unmaterialize', 'materialized' as const, true],
])(
'moves back to the last page when %s empties the filtered page',
async (_kind, typeFilter, startsMaterialized) => {
const views = Array.from({ length: PAGE_SIZE + 1 }, (_, i) => buildView(`v-${i}`, startsMaterialized))
useMocks({
get: { '/api/projects/:team_id/warehouse_saved_queries/': { count: views.length, results: views } },
})
dataWarehouseViewsLogic.actions.loadDataWarehouseSavedQueries()
await expectLogic(dataWarehouseViewsLogic).toFinishAllListeners()
logic.actions.setTypeFilter(typeFilter)
logic.actions.setPage(2)
const flipped = views.map((view, i) => (i === PAGE_SIZE ? buildView(`v-${i}`, !startsMaterialized) : view))
useMocks({
get: {
'/api/projects/:team_id/warehouse_saved_queries/': { count: flipped.length, results: flipped },
},
})
logic.actions.suggestionAccepted(`v-${PAGE_SIZE}`, !startsMaterialized)
await expectLogic(dataWarehouseViewsLogic).toFinishAllListeners()
expect(logic.values.currentPage).toEqual(1)
expect(logic.values.visibleViews).toHaveLength(PAGE_SIZE)
}
)
it('reloads the database schema so certification tags follow an accepted suggestion', async () => {
await expectLogic(logic, () => logic.actions.suggestionAccepted('mat-0', false)).toDispatchActions([
databaseTableListLogic.actionCreators.refreshDatabaseSchema(),
])
})
it('keeps polling an accepted materialize until the view reports it is materialized', async () => {
logic.actions.suggestionAccepted('plain-a', true)
await expectLogic(dataWarehouseViewsLogic).toFinishAllListeners()
expect(dataWarehouseViewsLogic.values.materializingViewIds).toEqual(['plain-a'])
})
it('keeps name matches visible while lineage data reloads', () => {
lineageDataLogic.actions.loadNodes()
logic.actions.setSearchTerm('+mat-1')
expect(logic.values.filteredViews.map((view) => view.id)).toEqual(['mat-1', 'mat-10'])
})
it('shows one success toast only after the confirmed deletion succeeds', async () => {
const dialog = jest.spyOn(LemonDialog, 'open').mockImplementation(() => {})
const toast = jest.spyOn(lemonToast, 'success').mockImplementation(() => '')
try {
logic.actions.deleteView('plain-a')
const confirm = dialog.mock.calls[0][0].primaryButton!.onClick!
confirm({} as React.MouseEvent<HTMLButtonElement>)
expect(toast).not.toHaveBeenCalled()
await expectLogic(dataWarehouseViewsLogic).toFinishAllListeners()
expect(toast).toHaveBeenCalledTimes(1)
expect(toast).toHaveBeenCalledWith('View deleted')
} finally {
dialog.mockRestore()
toast.mockRestore()
}
})
})