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.

8.5 KB
Raw Blame
import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'

import api from 'lib/api'
import { ApiError } from 'lib/api-error'
import * as takeOwnership from 'lib/components/openTakeOwnershipDialog'
import { urls } from 'scenes/urls'

import { AlertState } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { HogFunctionType } from '~/types'

import * as generatedApi from 'products/alerts/frontend/generated/api'

import { AlertType } from '../types'
import { alertsLogic } from './alertsLogic'

const alert = {
    id: 'alert-1',
    name: 'Checkout conversion dropped',
    calculation_interval: 'daily',
    condition: {},
    config: {},
    enabled: true,
    insight: { id: 1 },
    state: AlertState.NOT_FIRING,
    subscribed_users: [],
    threshold: { configuration: {} },
} as unknown as AlertType

describe('alertsLogic', () => {
    let deleteSpy: jest.SpyInstance
    let listSpy: jest.SpyInstance
    let hogFunctionsListSpy: jest.SpyInstance
    let updateSpy: jest.SpyInstance

    beforeEach(() => {
        initKeaTests()
        listSpy = jest.spyOn(api.alerts, 'list').mockResolvedValue({ results: [alert], count: 1 })
        hogFunctionsListSpy = jest.spyOn(api.hogFunctions, 'list').mockResolvedValue({ results: [], count: 0 })
    })

    afterEach(() => {
        deleteSpy?.mockRestore()
        listSpy.mockRestore()
        hogFunctionsListSpy.mockRestore()
        updateSpy?.mockRestore()
    })

    it('keeps the creator filter and URL in sync', async () => {
        router.actions.push(
            urls.alerts(),
            { tab: 'insights', alert_id: alert.id, created_by: 'creator-from-link' },
            { section: 'alerts' }
        )
        const logic = alertsLogic()
        logic.mount()
        await expectLogic(logic).toFinishAllListeners()
        expect(listSpy).toHaveBeenCalledTimes(1)
        expect(hogFunctionsListSpy).toHaveBeenCalledTimes(1)
        expect(logic.values.filters.createdBy).toEqual('creator-from-link')
        expect(listSpy).toHaveBeenLastCalledWith(
            undefined,
            expect.objectContaining({ created_by: 'creator-from-link' })
        )

        await expectLogic(logic, () => logic.actions.setFilters({ createdBy: 'creator-1' })).toFinishAllListeners()
        expect(router.values.searchParams).toEqual({
            tab: 'insights',
            alert_id: alert.id,
            created_by: 'creator-1',
        })
        expect(router.values.hashParams).toEqual({ section: 'alerts' })
        expect(listSpy).toHaveBeenLastCalledWith(undefined, expect.objectContaining({ created_by: 'creator-1' }))

        await expectLogic(logic, () => logic.actions.setFilters({ createdBy: 'All users' })).toFinishAllListeners()
        expect(router.values.searchParams).toEqual({ tab: 'insights', alert_id: alert.id })
        expect(listSpy.mock.lastCall?.[1]).not.toHaveProperty('created_by')

        await expectLogic(logic, () => router.actions.push(urls.alerts(), { created_by: 'creator-2' }))
            .toFinishAllListeners()
            .toMatchValues({ filters: { search: '', createdBy: 'creator-2' } })

        await expectLogic(logic, () => router.actions.push(urls.alerts()))
            .toFinishAllListeners()
            .toMatchValues({ filters: { search: '', createdBy: 'All users' } })
        logic.unmount()
    })

    it('keeps a deleted alert out of a reloaded list', async () => {
        deleteSpy = jest.spyOn(api.alerts, 'delete').mockResolvedValue()
        const nextAlert = { ...alert, id: 'alert-2', name: 'Newer alert' }
        listSpy.mockReset()
        listSpy
            .mockResolvedValueOnce({ results: [alert], count: 1 })
            .mockResolvedValueOnce({ results: [alert, nextAlert], count: 2 })

        const logic = alertsLogic()
        logic.mount()
        await expectLogic(logic).toFinishAllListeners()

        await expectLogic(logic, () => logic.actions.deleteAlert(alert)).toFinishAllListeners()

        expect(deleteSpy).toHaveBeenCalledWith(alert.id)
        expect(listSpy).toHaveBeenCalledTimes(2)
        expect(logic.values.alertsResponse).toEqual({ results: [nextAlert], count: 1 })

        logic.unmount()
    })

    it('keeps the delete action disabled while deleting', async () => {
        let resolveDelete: () => void = () => {}
        const deletePromise = new Promise<void>((resolve) => {
            resolveDelete = resolve
        })
        deleteSpy = jest.spyOn(api.alerts, 'delete').mockReturnValue(deletePromise)

        const logic = alertsLogic()
        logic.mount()
        await expectLogic(logic).toFinishAllListeners()

        logic.actions.deleteAlert(alert)
        expect(logic.values.deletingAlertIds).toEqual(new Set([alert.id]))

        resolveDelete()

        await expectLogic(logic).toFinishAllListeners().toMatchValues({ deletingAlertIds: new Set() })
        logic.unmount()
    })

    it('offers to take ownership when enabling is refused for the owner, then reloads', async () => {
        updateSpy = jest
            .spyOn(api.alerts, 'update')
            .mockRejectedValue(new ApiError('refused', 400, undefined, { code: 'owner_lost_access' }))
        const takeSpy = jest.spyOn(generatedApi, 'alertsTakeOwnershipCreate').mockResolvedValue({} as any)
        const dialogSpy = jest
            .spyOn(takeOwnership, 'openTakeOwnershipDialog')
            .mockImplementation(async ({ takeOwnership: take }) => {
                await take()
                return true
            })

        const logic = alertsLogic()
        logic.mount()
        await expectLogic(logic).toFinishAllListeners()
        listSpy.mockClear()

        logic.actions.toggleAlertEnabled({ ...alert, enabled: false })
        await expectLogic(logic).toFinishAllListeners()

        expect(dialogSpy).toHaveBeenCalledWith(
            expect.objectContaining({ resourceLabel: 'alert', resourceId: alert.id, cause: 'lost_access' })
        )
        expect(takeSpy).toHaveBeenCalledWith(expect.any(String), alert.id)
        expect(listSpy).toHaveBeenCalledTimes(1)
        expect(logic.values.togglingAlertIds).toEqual(new Set())

        takeSpy.mockRestore()
        dialogSpy.mockRestore()
        logic.unmount()
    })

    it('keeps the alert toggle loading and patches the latest alert list', async () => {
        let resolveUpdate: (updatedAlert: AlertType) => void = () => {}
        const updatePromise = new Promise<AlertType>((resolve) => {
            resolveUpdate = resolve
        })
        updateSpy = jest.spyOn(api.alerts, 'update').mockReturnValue(updatePromise)

        const logic = alertsLogic()
        logic.mount()
        await expectLogic(logic).toFinishAllListeners()

        logic.actions.toggleAlertEnabled(alert)

        expect(updateSpy).toHaveBeenCalledWith(alert.id, { enabled: false })
        expect(logic.values.togglingAlertIds).toEqual(new Set([alert.id]))

        const alertFromNewerList = { ...alert, id: 'alert-2', name: 'Newer filtered result' }
        logic.actions.loadAlertsSuccess({ results: [alert, alertFromNewerList], count: 2 })

        resolveUpdate({ ...alert, enabled: false })

        await expectLogic(logic)
            .toFinishAllListeners()
            .toMatchValues({
                alertsResponse: {
                    results: [{ ...alert, enabled: false }, alertFromNewerList],
                    count: 2,
                },
                togglingAlertIds: new Set(),
            })

        logic.unmount()
    })

    it('counts only enabled destinations for alerts on the current page', async () => {
        hogFunctionsListSpy.mockResolvedValue({
            count: 3,
            results: [
                {
                    id: 'destination-1',
                    enabled: true,
                    filters: { properties: [{ key: 'alert_id', value: alert.id }] },
                },
                {
                    id: 'destination-2',
                    enabled: false,
                    filters: { properties: [{ key: 'alert_id', value: alert.id }] },
                },
                {
                    id: 'destination-for-other-alert',
                    enabled: true,
                    filters: { properties: [{ key: 'alert_id', value: 'other-alert' }] },
                },
            ] as unknown as HogFunctionType[],
        })

        const logic = alertsLogic()
        logic.mount()

        await expectLogic(logic)
            .toFinishAllListeners()
            .toMatchValues({
                alertDestinationCounts: { [alert.id]: 1 },
            })

        logic.unmount()
    })
})