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.

6.8 KB
Raw Blame
import { MOCK_TEAM_ID } from 'lib/api.mock'

import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'

import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import type { Experiment } from '~/types'

import { NEW_EXPERIMENT } from 'products/experiments/frontend/constants'

import { createExperimentLogic } from './createExperimentLogic'

describe('ExperimentForm Integration', () => {
    let logic: ReturnType<typeof createExperimentLogic.build>
    let routerPushSpy: jest.SpyInstance

    beforeEach(() => {
        // Clear localStorage to prevent persisted state from affecting tests
        localStorage.clear()
        // Drafts persist in sessionStorage; clear so one test's draft can't leak into the next
        sessionStorage.clear()

        useMocks({
            post: {
                [`/api/projects/${MOCK_TEAM_ID}/experiments`]: async ({ request }) => {
                    const body = (await request.json()) as Experiment
                    return [
                        200,
                        {
                            id: 123,
                            name: body.name,
                            description: body.description,
                            type: body.type || 'product',
                            feature_flag: { id: 456 },
                        },
                    ]
                },
            },
            patch: {
                '/api/environments/:team_id/add_product_intent/': () => [200, {}],
            },
        })
        initKeaTests()
        logic = createExperimentLogic()
        logic.mount()
        routerPushSpy = jest.spyOn(router.actions, 'push')
        jest.clearAllMocks()
    })

    afterEach(() => {
        logic.unmount()
        routerPushSpy.mockRestore()
    })

    describe('form state and validation', () => {
        it('initializes with default NEW_EXPERIMENT values', async () => {
            await expectLogic(logic).toMatchValues({
                experiment: expect.objectContaining({
                    id: 'new',
                    name: '',
                    description: '',
                    type: 'product',
                }),
            })
        })

        it('updates experiment state through setExperiment', async () => {
            await expectLogic(logic, () => {
                logic.actions.setExperiment({
                    ...NEW_EXPERIMENT,
                    name: 'My Test Experiment',
                    description: 'My hypothesis',
                })
            }).toMatchValues({
                experiment: expect.objectContaining({
                    name: 'My Test Experiment',
                    description: 'My hypothesis',
                }),
            })
        })

        it('validates and prevents submission with empty fields', async () => {
            await expectLogic(logic, () => {
                logic.actions.setExperiment({ ...NEW_EXPERIMENT, name: '' })
                logic.actions.saveExperiment()
            })
                .toDispatchActions(['saveExperiment', 'saveExperimentFailure'])
                .toMatchValues({
                    experimentErrors: expect.objectContaining({
                        name: 'Name is required',
                    }),
                })
        })
    })

    describe('experiment type changes', () => {
        it('allows changing experiment type from product to web', async () => {
            await expectLogic(logic, () => {
                logic.actions.setExperiment({ ...NEW_EXPERIMENT, type: 'web' })
            }).toMatchValues({
                experiment: expect.objectContaining({
                    type: 'web',
                }),
            })
        })

        it('defaults to product experiment type', async () => {
            await expectLogic(logic).toMatchValues({
                experiment: expect.objectContaining({
                    type: 'product',
                }),
            })
        })
    })

    describe('full submission flow', () => {
        it('successfully submits valid experiment and navigates to view page', async () => {
            await expectLogic(logic, () => {
                logic.actions.setExperiment({
                    ...NEW_EXPERIMENT,
                    name: 'Test Experiment',
                    description: 'Test hypothesis',
                    feature_flag_key: 'test-experiment',
                })
                logic.actions.saveExperiment()
            })
                .toDispatchActions(['saveExperiment', 'createExperimentSuccess'])
                .toFinishAllListeners()

            expect(routerPushSpy).toHaveBeenCalledWith('/experiments/123')
        })

        it('clears errors after successful submission', async () => {
            await expectLogic(logic, () => {
                logic.actions.setExperiment({ ...NEW_EXPERIMENT, name: '', description: '' })
                logic.actions.saveExperiment()
            }).toMatchValues({
                experimentErrors: expect.objectContaining({
                    name: 'Name is required',
                }),
            })

            await expectLogic(logic, () => {
                logic.actions.setExperiment({
                    ...NEW_EXPERIMENT,
                    name: 'Valid Name',
                    description: 'Valid Description',
                    feature_flag_key: 'valid-experiment',
                })
                logic.actions.saveExperiment()
            })
                .toDispatchActions(['saveExperiment', 'createExperimentSuccess'])
                .toMatchValues({
                    experimentErrors: {},
                })
        })

        it('still prevents submission if data remains invalid after clearing old errors', async () => {
            // First attempt - missing name
            await expectLogic(logic, () => {
                logic.actions.setExperiment({ ...NEW_EXPERIMENT, name: '' })
                logic.actions.saveExperiment()
            })
                .toDispatchActions(['saveExperiment', 'saveExperimentFailure'])
                .toMatchValues({
                    experimentErrors: expect.objectContaining({
                        name: 'Name is required',
                    }),
                })

            // Second attempt - has name but missing feature_flag_key (still invalid)
            await expectLogic(logic, () => {
                logic.actions.setExperiment({
                    ...NEW_EXPERIMENT,
                    name: 'Valid Name',
                    description: 'Valid Description',
                    feature_flag_key: '', // Missing - should still fail
                })
                logic.actions.saveExperiment()
            }).toDispatchActions(['saveExperiment', 'saveExperimentFailure'])

            // Verify it didn't succeed
            expect(routerPushSpy).not.toHaveBeenCalled()
        })
    })
})