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.

7.8 KB
Raw Blame
import { renderHook, waitFor } from '@testing-library/react'
import { useValues } from 'kea'
import posthog from 'posthog-js'

import api from '~/lib/api'

import { membersList, rolesList } from 'products/platform_features/frontend/generated/api'

import * as accessControlHclExporter from './accessControlHclExporter'
import * as dashboardHclExporter from './dashboardHclExporter'
import * as insightHclExporter from './insightHclExporter'
import { TerraformExportResource, useTerraformExport } from './useTerraformExport'

jest.mock('~/lib/api')
jest.mock('posthog-js')
jest.mock('products/platform_features/frontend/generated/api', () => ({
    rolesList: jest.fn(),
    membersList: jest.fn(),
}))
jest.mock('kea', () => ({
    ...jest.requireActual('kea'),
    useValues: jest.fn(),
}))

const mockedApi = api as jest.Mocked<typeof api>

describe('useTerraformExport', () => {
    beforeEach(() => {
        jest.clearAllMocks()
        ;(useValues as jest.Mock).mockReturnValue({ currentTeamId: 1 })
        jest.spyOn(mockedApi.alerts, 'list').mockResolvedValue({ results: [] } as any)
        jest.spyOn(mockedApi.hogFunctions, 'list').mockResolvedValue({ results: [] } as any)
    })

    describe('error handling', () => {
        it('catches generateInsightHCL errors and provides descriptive message', async () => {
            const insightResource: TerraformExportResource = {
                type: 'insight',
                data: {
                    id: 123,
                    name: 'My Test Insight',
                },
            }

            jest.spyOn(insightHclExporter, 'generateInsightHCL').mockImplementation(() => {
                throw new Error('Cannot read property of null')
            })

            const { result } = renderHook(() => useTerraformExport(insightResource, true))

            await waitFor(() => {
                expect(result.current.loading).toBe(false)
            })

            expect(result.current.error).toBe(
                'Failed to generate HCL for insight "My Test Insight" (123): Cannot read property of null'
            )
            expect(result.current.result).toBeNull()
        })

        it('catches generateDashboardHCL errors and provides descriptive message', async () => {
            const dashboardResource: TerraformExportResource = {
                type: 'dashboard',
                data: {
                    id: 456,
                    name: 'My Test Dashboard',
                    tiles: [],
                } as any,
            }

            jest.spyOn(dashboardHclExporter, 'generateDashboardHCL').mockImplementation(() => {
                throw new Error('Unexpected null value')
            })

            const { result } = renderHook(() => useTerraformExport(dashboardResource, true))

            await waitFor(() => {
                expect(result.current.loading).toBe(false)
            })

            expect(result.current.error).toBe(
                'Failed to generate HCL for dashboard "My Test Dashboard" (456): Unexpected null value'
            )
            expect(result.current.result).toBeNull()
        })

        it('captures errors to PostHog with context', async () => {
            const insightResource: TerraformExportResource = {
                type: 'insight',
                data: {
                    id: 789,
                    name: 'Tracked Insight',
                },
            }

            const testError = new Error('Test error for tracking')
            jest.spyOn(insightHclExporter, 'generateInsightHCL').mockImplementation(() => {
                throw testError
            })

            const { result } = renderHook(() => useTerraformExport(insightResource, true))

            await waitFor(() => {
                expect(result.current.loading).toBe(false)
            })

            expect(posthog.captureException).toHaveBeenCalledWith(
                expect.objectContaining({
                    message: 'Failed to generate HCL for insight "Tracked Insight" (789): Test error for tracking',
                }),
                {
                    extra: {
                        context: 'TerraformExporter',
                        resourceType: 'insight',
                        resourceId: 789,
                    },
                }
            )
        })

        it('captures access control export errors with the project id', async () => {
            mockedApi.get.mockResolvedValue({ access_controls: [] })
            ;(rolesList as jest.Mock).mockResolvedValue({ results: [], next: null })
            ;(membersList as jest.Mock).mockResolvedValue({ results: [], next: null })
            jest.spyOn(accessControlHclExporter, 'generateAccessControlHCL').mockImplementation(() => {
                throw new Error('Test error for tracking')
            })
            const accessControlResource: TerraformExportResource = {
                type: 'access_control',
                data: { projectId: 73, projectName: 'Test project', organizationId: 'org-1' },
            }

            const { result } = renderHook(() => useTerraformExport(accessControlResource, true))

            await waitFor(() => {
                expect(result.current.loading).toBe(false)
            })

            expect(result.current.error).toBe('Test error for tracking')
            expect(posthog.captureException).toHaveBeenCalledWith(expect.any(Error), {
                extra: { context: 'TerraformExporter', resourceType: 'access_control', resourceId: 73 },
            })
        })

        it('handles non-Error exceptions gracefully', async () => {
            const insightResource: TerraformExportResource = {
                type: 'insight',
                data: {
                    id: 999,
                    name: 'Test Insight',
                },
            }

            jest.spyOn(insightHclExporter, 'generateInsightHCL').mockImplementation(() => {
                throw 'String error instead of Error object'
            })

            const { result } = renderHook(() => useTerraformExport(insightResource, true))

            await waitFor(() => {
                expect(result.current.loading).toBe(false)
            })

            expect(result.current.error).toBe(
                'Failed to generate HCL for insight "Test Insight" (999): String error instead of Error object'
            )
        })
    })

    describe('successful export', () => {
        it('returns result on successful insight export', async () => {
            const insightResource: TerraformExportResource = {
                type: 'insight',
                data: {
                    id: 123,
                    name: 'Working Insight',
                },
            }

            const mockResult = {
                hcl: 'resource "posthog_insight" "working_insight" {}',
                warnings: [],
                resourceCounts: { dashboards: 0, insights: 1, alerts: 0, hogFunctions: 0 },
            }

            jest.spyOn(insightHclExporter, 'generateInsightHCL').mockReturnValue(mockResult)

            const { result } = renderHook(() => useTerraformExport(insightResource, true))

            await waitFor(() => {
                expect(result.current.loading).toBe(false)
            })

            expect(result.current.error).toBeNull()
            expect(result.current.result).toEqual(mockResult)
        })
    })

    describe('loading state', () => {
        it('does not fetch when modal is closed', () => {
            const insightResource: TerraformExportResource = {
                type: 'insight',
                data: {
                    id: 123,
                    name: 'Test',
                },
            }

            const generateSpy = jest.spyOn(insightHclExporter, 'generateInsightHCL')

            renderHook(() => useTerraformExport(insightResource, false))

            expect(generateSpy).not.toHaveBeenCalled()
        })
    })
})