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.6 KB
Raw Blame
import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'

import { initKeaTests } from '~/test/init'

import { visionObservationsLabelCreate } from '../generated/api'
import { observationLabelLogic } from './observationLabelLogic'

jest.mock('../generated/api', () => ({
    visionObservationsLabelCreate: jest.fn(),
    visionObservationsLabelDestroy: jest.fn(),
}))

const TEAM_ID = String(MOCK_DEFAULT_TEAM.id)

describe('observationLabelLogic feedback autosave', () => {
    let logic: ReturnType<typeof observationLabelLogic.build>
    let onChange: jest.Mock

    const mountLogic = (isCorrect: boolean): void => {
        logic = observationLabelLogic({
            observationId: 'obs-1',
            initialLabel: { is_correct: isCorrect, feedback: 'old feedback' },
            onChange,
        })
        logic.mount()
    }

    beforeEach(() => {
        jest.clearAllMocks()
        initKeaTests()
        ;(visionObservationsLabelCreate as jest.Mock).mockImplementation((_team, _id, body) =>
            Promise.resolve({ ...body })
        )
        onChange = jest.fn()
        jest.useFakeTimers()
    })

    afterEach(() => {
        jest.useRealTimers()
        logic?.unmount()
    })

    it.each([
        ['thumbs-down', false],
        ['thumbs-up', true],
    ])('autosaves edited feedback on a %s rating after the debounce and notifies onChange', async (_, isCorrect) => {
        mountLogic(isCorrect)
        logic.actions.setFeedbackDraft('scanner missed the refund step')
        await jest.advanceTimersByTimeAsync(900)

        expect(visionObservationsLabelCreate).toHaveBeenCalledTimes(1)
        expect(visionObservationsLabelCreate).toHaveBeenCalledWith(TEAM_ID, 'obs-1', {
            is_correct: isCorrect,
            feedback: 'scanner missed the refund step',
        })
        expect(onChange).toHaveBeenCalledWith({ is_correct: isCorrect, feedback: 'scanner missed the refund step' })
    })

    it('saves a note typed just before the page unmounts, which cancels the pending autosave', async () => {
        mountLogic(false)
        logic.actions.setFeedbackDraft('wrong: the user finished checkout')
        await jest.advanceTimersByTimeAsync(300)
        logic.unmount()

        expect(visionObservationsLabelCreate).toHaveBeenCalledTimes(1)
        expect(visionObservationsLabelCreate).toHaveBeenCalledWith(TEAM_ID, 'obs-1', {
            is_correct: false,
            feedback: 'wrong: the user finished checkout',
        })
    })

    it('keeps a rating still in flight when the page unmounts with an unsaved note', async () => {
        mountLogic(true)
        ;(visionObservationsLabelCreate as jest.Mock).mockImplementationOnce(() => new Promise(() => {}))
        logic.actions.rate(false, 'old feedback')
        logic.actions.setFeedbackDraft('it missed the declined card')
        logic.unmount()

        expect(visionObservationsLabelCreate).toHaveBeenLastCalledWith(TEAM_ID, 'obs-1', {
            is_correct: false,
            feedback: 'it missed the declined card',
        })
    })

    it('settles as synced when the API trims the feedback it stores', async () => {
        // The API trims before storing, so the echoed label never matches a draft with trailing whitespace.
        ;(visionObservationsLabelCreate as jest.Mock).mockImplementation((_team, _id, body) =>
            Promise.resolve({ ...body, feedback: body.feedback.trim() })
        )
        mountLogic(false)
        logic.actions.setFeedbackDraft('scanner missed the refund step\n')
        await jest.advanceTimersByTimeAsync(900)

        expect(logic.values.feedbackSynced).toBe(true)
        expect(logic.values.saving).toBe(false)
        // The stored value already covers the draft, so an unchanged draft must not keep resaving.
        logic.actions.setFeedbackDraft('scanner missed the refund step  ')
        await jest.advanceTimersByTimeAsync(900)
        expect(visionObservationsLabelCreate).toHaveBeenCalledTimes(1)
    })

    it('reports a failed autosave instead of staying on saving', async () => {
        ;(visionObservationsLabelCreate as jest.Mock).mockRejectedValue({ detail: 'nope' })
        mountLogic(false)
        logic.actions.setFeedbackDraft('scanner missed the refund step')
        await jest.advanceTimersByTimeAsync(900)

        expect(logic.values.saveFailed).toBe(true)
        expect(logic.values.saving).toBe(false)
    })

    it('a rating click during the debounce wins over the pending autosave', async () => {
        mountLogic(false)
        logic.actions.setFeedbackDraft('scanner missed the refund step')
        logic.actions.rate(true, '')
        await jest.advanceTimersByTimeAsync(900)

        expect(visionObservationsLabelCreate).toHaveBeenCalledTimes(1)
        expect(visionObservationsLabelCreate).toHaveBeenCalledWith(TEAM_ID, 'obs-1', {
            is_correct: true,
            feedback: '',
        })
    })

    it('adopts a remote label change from props but keeps the draft on a same-label re-render', async () => {
        mountLogic(false)
        logic.actions.setFeedbackDraft('half-typed local edit')

        // Parent re-renders with the unchanged label: the local draft must survive.
        observationLabelLogic({
            observationId: 'obs-1',
            initialLabel: { is_correct: false, feedback: 'old feedback' },
            onChange,
        })
        expect(logic.values.feedbackDraft).toEqual('half-typed local edit')

        // Observation reloads with a teammate's newer label: adopt it and drop the pending autosave.
        observationLabelLogic({
            observationId: 'obs-1',
            initialLabel: { is_correct: true, feedback: 'teammate feedback' },
            onChange,
        })
        await jest.advanceTimersByTimeAsync(900)

        expect(visionObservationsLabelCreate).not.toHaveBeenCalled()
        expect(logic.values.label).toEqual({ is_correct: true, feedback: 'teammate feedback' })
        expect(logic.values.feedbackDraft).toEqual('teammate feedback')
    })

    it("keeps a teammate's adopted rating when an edited note saves on unmount", async () => {
        mountLogic(false)
        logic.actions.rate(true, 'old feedback')
        await jest.advanceTimersByTimeAsync(0)
        observationLabelLogic({
            observationId: 'obs-1',
            initialLabel: { is_correct: false, feedback: 'teammate feedback' },
            onChange,
        })
        logic.actions.setFeedbackDraft('teammate feedback, plus mine')
        logic.unmount()

        expect(visionObservationsLabelCreate).toHaveBeenLastCalledWith(TEAM_ID, 'obs-1', {
            is_correct: false,
            feedback: 'teammate feedback, plus mine',
        })
    })
})