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.

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

jest.mock('lib/lemon-ui/LemonToast/LemonToast', () => ({
    lemonToast: { success: jest.fn(), error: jest.fn() },
}))

import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { initKeaTests } from '~/test/init'
import { toolbarConfigLogic } from '~/toolbar/shared/toolbarConfigLogic'

import { experimentsLogic } from './experimentsLogic'

// The toolbar logger mirrors intentional error/auth paths to the console (its job on
// customer pages); tests exercise those paths on purpose, so stub the boundary.
jest.mock('~/toolbar/shared/toolbarLogger', () => ({
    toolbarLogger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },
}))

const web_experiments = [{ id: 1, name: 'Test Experiment 1', variants: {} }]

function mockFetch(response: Partial<Response> & { json?: () => Promise<unknown> }): void {
    global.fetch = jest.fn(() => Promise.resolve(response as Response))
}

describe('experimentsLogic', () => {
    // These suites intentionally reject requests to exercise error states; the
    // failures are asserted via authStatus/values, so skip the global loader logging.
    beforeAll(silenceKeaLoadersErrors)
    afterAll(resumeKeaLoadersErrors)

    let logic: ReturnType<typeof experimentsLogic.build>
    const savedFetch = global.fetch

    afterAll(() => {
        global.fetch = savedFetch
    })

    function mountLogic({ withToken = true }: { withToken?: boolean } = {}): void {
        initKeaTests()
        toolbarConfigLogic
            .build({ apiURL: 'http://localhost', ...(withToken ? { accessToken: 'test-token' } : {}) })
            .mount()
        logic = experimentsLogic()
        logic.mount()
    }

    it('loads experiments on a successful response', async () => {
        mockFetch({ ok: true, status: 200, json: () => Promise.resolve({ results: web_experiments }) })
        mountLogic()

        await expectLogic(logic, () => {
            logic.actions.getExperiments()
        })
            .toDispatchActions(['getExperiments', 'getExperimentsSuccess'])
            .toMatchValues({ allExperiments: web_experiments })
    })

    it('returns an empty list when unauthenticated (stubbed 401)', async () => {
        // No access token → toolbarFetch short-circuits to a stubbed 401, never hitting fetch.
        mountLogic({ withToken: false })

        await expectLogic(logic, () => {
            logic.actions.getExperiments()
        })
            .toDispatchActions(['getExperiments', 'getExperimentsSuccess'])
            .toMatchValues({ allExperiments: [] })
    })

    it('soft-fails to an empty list on a 5xx server error', async () => {
        mockFetch({ ok: false, status: 503, json: () => Promise.reject(new Error('unused')) })
        mountLogic()

        await expectLogic(logic, () => {
            logic.actions.getExperiments()
        })
            .toDispatchActions(['getExperiments', 'getExperimentsSuccess'])
            .toMatchValues({ allExperiments: [] })
    })

    it.each([
        ['a non-2xx response', { ok: false, status: 404, json: () => Promise.resolve({}) }],
        [
            'the body is not valid JSON',
            { ok: true, status: 200, json: () => Promise.reject(new Error('Unexpected token')) },
        ],
        [
            'results is not an array',
            { ok: true, status: 200, json: () => Promise.resolve({ results: { unexpected: true } }) },
        ],
    ] as [string, Partial<Response> & { json?: () => Promise<unknown> }][])(
        'soft-fails to an empty list when %s',
        async (_name, fetchResponse) => {
            mockFetch(fetchResponse)
            mountLogic()

            await expectLogic(logic, () => {
                logic.actions.getExperiments()
            })
                .toDispatchActions(['getExperiments', 'getExperimentsSuccess'])
                .toMatchValues({ allExperiments: [] })
        }
    )
})