[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6E34XZGR9E65DK9NVDGEP51":3,"skill-same:01M6E34XZGR9E65DK9NVDGEP51":79},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":45,"linkOnly":46,"markdownContent":47,"markdownBody":48,"frontMatter":49,"refName":50,"commitSha":51,"skillDirectory":52,"forksCount":53,"repositoryHtmlUrl":54,"repositoryHomepageUrl":55,"ownerHtmlUrl":56,"ownerBlogUrl":6,"ownerDescription":57,"updatedAt":58,"install":59,"resources":72},"01M6E34XZGR9E65DK9NVDGEP51","bubbletea-testing",null,"Use this skill whenever writing tests for Bubble Tea (charmbracelet\u002Fbubbletea) TUI applications in Go. Triggers include any mention of testing Bubble Tea models, teatest, golden file testing for TUIs, testing tea.Cmd or tea.Msg, snapshot testing terminal output, or writing tests for any Go CLI\u002FTUI that uses the Elm Architecture (Init\u002FUpdate\u002FView). Also use when the user asks about testing bubbletea components, bubbles, or lipgloss-styled views, or when they need CI-friendly TUI test patterns. Even if they just say \"test my TUI\" or \"add tests to my Bubble Tea app\", use this skill.","dimetron\u002Fpi-go","dimetron","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F877433?v=4","01M6E34QX9HKYKMWJVZQEPR2Q3","Dmytro Rashko","01M6E34R2A6563XM0PTZE8KPGG",224,"MIT","https:\u002F\u002Fgithub.com\u002Fdimetron\u002Fpi-go\u002Fblob\u002Fmain\u002F.pi-go\u002Fskills\u002Fbubbletea-testing\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],"bubbletea","bubbletea testing","testing","snapshot","bubble tea","for","snapshot testing","add","golden","app","triggers","tests","patterns","use","view","just","applications","ci","update","architecture","init","components","go","terminal","cli","writing","2026-11-10 10:12:30",false,"---\nname: bubbletea-testing\ndescription: Use this skill whenever writing tests for Bubble Tea (charmbracelet\u002Fbubbletea) TUI applications in Go. Triggers include any mention of testing Bubble Tea models, teatest, golden file testing for TUIs, testing tea.Cmd or tea.Msg, snapshot testing terminal output, or writing tests for any Go CLI\u002FTUI that uses the Elm Architecture (Init\u002FUpdate\u002FView). Also use when the user asks about testing bubbletea components, bubbles, or lipgloss-styled views, or when they need CI-friendly TUI test patterns. Even if they just say \"test my TUI\" or \"add tests to my Bubble Tea app\", use this skill.\n---\n\n# Bubble Tea Testing\n\nWrite robust, CI-friendly tests for Bubble Tea TUI applications using a three-layer strategy: direct model unit tests, golden file view snapshots, and full-program integration tests via `teatest`.\n\n## Architecture overview\n\nBubble Tea's Elm Architecture (`Init`, `Update`, `View`) makes TUI apps inherently testable. `Update(msg) -> (model, cmd)` is a pure function of state and message — no terminal, program, or event loop needed for most tests.\n\n**Three-layer strategy:**\n\n| Layer | Coverage | Speed | Tool |\n|-------|----------|-------|------|\n| 1. Direct model tests | State transitions, commands, view content | ~ms | Standard `testing` |\n| 2. Golden file snapshots | Visual regression on `View()` output | ~ms | `golden.RequireEqual` |\n| 3. Full integration | End-to-end user flows | ~seconds | `teatest.NewTestModel` |\n\nTarget ratio: **80% Layer 1 \u002F 15% Layer 2 \u002F 5% Layer 3**.\n\n---\n\n## Layer 1: Direct model unit tests\n\n### Constructing test messages\n\nBuild `tea.Msg` values directly — they are plain Go structs:\n\n```go\n\u002F\u002F v1\nqKey   := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")}\nenter  := tea.KeyMsg{Type: tea.KeyEnter}\nctrlC  := tea.KeyMsg{Type: tea.KeyCtrlC}\ndown   := tea.KeyMsg{Type: tea.KeyDown}\nresize := tea.WindowSizeMsg{Width: 80, Height: 24}\n\n\u002F\u002F v2 renames\nqKey   := tea.KeyPressMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")}\nclick  := tea.MouseClickMsg{X: 10, Y: 5, Button: tea.MouseButtonLeft}\n```\n\n### Table-driven Update tests\n\nThe standard pattern — each case specifies initial state, message, and expected outcome:\n\n```go\nfunc TestUpdate(t *testing.T) {\n    tests := []struct {\n        name       string\n        initial    model\n        msg        tea.Msg\n        wantCursor int\n        wantQuit   bool\n    }{\n        {\n            name:       \"down moves cursor\",\n            initial:    model{cursor: 0, choices: []string{\"a\", \"b\", \"c\"}},\n            msg:        tea.KeyMsg{Type: tea.KeyDown},\n            wantCursor: 1,\n        },\n        {\n            name:       \"cursor stops at bottom\",\n            initial:    model{cursor: 2, choices: []string{\"a\", \"b\", \"c\"}},\n            msg:        tea.KeyMsg{Type: tea.KeyDown},\n            wantCursor: 2,\n        },\n        {\n            name:       \"q triggers quit\",\n            initial:    model{},\n            msg:        tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")},\n            wantQuit:   true,\n        },\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            updated, cmd := tt.initial.Update(tt.msg)\n            m := updated.(model)\n\n            if m.cursor != tt.wantCursor {\n                t.Errorf(\"cursor = %d, want %d\", m.cursor, tt.wantCursor)\n            }\n            if tt.wantQuit {\n                if cmd == nil {\n                    t.Fatal(\"expected quit command\")\n                }\n                if _, ok := cmd().(tea.QuitMsg); !ok {\n                    t.Error(\"quit command did not return QuitMsg\")\n                }\n            }\n        })\n    }\n}\n```\n\n### Testing commands synchronously\n\n`tea.Cmd` is `func() tea.Msg`. Execute it directly and inspect the result:\n\n```go\nfunc TestQuitCommand(t *testing.T) {\n    m := model{}\n    _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")})\n\n    if cmd == nil {\n        t.Fatal(\"expected quit command\")\n    }\n    msg := cmd() \u002F\u002F execute synchronously\n    if _, ok := msg.(tea.QuitMsg); !ok {\n        t.Errorf(\"expected QuitMsg, got %T\", msg)\n    }\n}\n```\n\n### Mocking I\u002FO dependencies\n\nUse interfaces for anything that does real I\u002FO, inject mocks in tests:\n\n```go\ntype DataFetcher interface {\n    FetchItems() ([]Item, error)\n}\n\ntype model struct {\n    fetcher DataFetcher\n    items   []Item\n}\n\n\u002F\u002F Test mock\ntype mockFetcher struct {\n    items []Item\n    err   error\n}\nfunc (f mockFetcher) FetchItems() ([]Item, error) { return f.items, f.err }\n\nfunc TestFetchSuccess(t *testing.T) {\n    m := model{fetcher: mockFetcher{items: []Item{{Name: \"test\"}}}}\n    cmd := m.fetchCmd()\n    msg := cmd()\n    result, ok := msg.(itemsMsg)\n    if !ok {\n        t.Fatalf(\"expected itemsMsg, got %T\", msg)\n    }\n    if len(result.items) != 1 {\n        t.Errorf(\"expected 1 item, got %d\", len(result.items))\n    }\n}\n```\n\n### Chaining update–command–message cycles\n\nSimulate multi-step flows without a running program:\n\n```go\nfunc TestMultiStepFlow(t *testing.T) {\n    m := tea.Model(initialModel())\n    var cmd tea.Cmd\n\n    \u002F\u002F Step 1: user presses enter\n    m, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})\n\n    \u002F\u002F Step 2: execute the resulting command, feed msg back\n    if cmd != nil {\n        m, cmd = m.Update(cmd())\n    }\n\n    \u002F\u002F Assert final state\n    final := m.(myModel)\n    if final.state != resultView {\n        t.Errorf(\"expected resultView, got %v\", final.state)\n    }\n}\n```\n\n### Testing View output with substring assertions\n\nPrefer substring checks over exact matches — more resilient to styling changes:\n\n```go\nfunc TestViewShowsSelection(t *testing.T) {\n    m := model{\n        cursor:   1,\n        choices:  []string{\"carrots\", \"celery\", \"kohlrabi\"},\n        selected: map[int]struct{}{1: {}},\n    }\n    view := m.View()\n\n    if !strings.Contains(view, \"[x] celery\") {\n        t.Errorf(\"expected selected celery in view:\\n%s\", view)\n    }\n    if !strings.Contains(view, \"[ ] carrots\") {\n        t.Errorf(\"expected unselected carrots in view:\\n%s\", view)\n    }\n}\n```\n\n**Principle:** Assert on intent (flags, indices, content), not styling.\n\n### Testing nested\u002Fcomposed models\n\nTest parent routing and child transitions independently:\n\n```go\nfunc TestParentRoutesToActiveChild(t *testing.T) {\n    parent := newParentModel()\n    updated, _ := parent.Update(tea.WindowSizeMsg{Width: 80, Height: 24})\n    p := updated.(parentModel)\n\n    child := p.list.(listModel)\n    if child.width != 80 {\n        t.Errorf(\"child width = %d, want 80\", child.width)\n    }\n}\n```\n\n---\n\n## Layer 2: Golden file testing\n\n### Packages\n\n| Package | Import | Use case |\n|---------|--------|----------|\n| `golden` | `github.com\u002Fcharmbracelet\u002Fx\u002Fexp\u002Fgolden` | Component-level View snapshots |\n| `teatest` | `github.com\u002Fcharmbracelet\u002Fx\u002Fexp\u002Fteatest` | Full-program output snapshots |\n\n### Component snapshot with `golden.RequireEqual`\n\n```go\nimport \"github.com\u002Fcharmbracelet\u002Fx\u002Fexp\u002Fgolden\"\n\nfunc TestTableRendering(t *testing.T) {\n    tbl := table.New(\n        table.WithColumns(columns),\n        table.WithRows(rows),\n    )\n    \u002F\u002F Compares against testdata\u002FTestTableRendering.golden\n    golden.RequireEqual(t, tbl.View())\n}\n```\n\n`golden.RequireEqual` auto-escapes ANSI codes and uses `go-udiff` for portable diffs.\n\n### Full-program snapshot with `teatest.RequireEqualOutput`\n\n```go\nfunc TestFullOutput(t *testing.T) {\n    tm := teatest.NewTestModel(t, initialModel(),\n        teatest.WithInitialTermSize(80, 24),\n    )\n    tm.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")})\n\n    out, _ := io.ReadAll(tm.FinalOutput(t, teatest.WithFinalTimeout(3*time.Second)))\n    \u002F\u002F Compares against testdata\u002FTestFullOutput.golden\n    teatest.RequireEqualOutput(t, out)\n}\n```\n\n### Golden file workflow\n\n```bash\n# 1. Generate initial golden files\ngo test .\u002F... -update\n\n# 2. Commit them\ngit add testdata\u002F*.golden\n\n# 3. Normal test runs — fails if output differs\ngo test .\u002F...\n\n# 4. After intentional UI changes — regenerate and review diff\ngo test .\u002F... -update\ngit diff testdata\u002F\n```\n\n---\n\n## Layer 3: Full integration with teatest\n\n### Core API\n\n```go\nimport (\n    \"bytes\"\n    \"io\"\n    \"testing\"\n    \"time\"\n\n    tea \"github.com\u002Fcharmbracelet\u002Fbubbletea\"\n    \"github.com\u002Fcharmbracelet\u002Fx\u002Fexp\u002Fteatest\"\n)\n\nfunc TestIntegration(t *testing.T) {\n    tm := teatest.NewTestModel(t, initialModel(),\n        teatest.WithInitialTermSize(80, 24),\n    )\n\n    \u002F\u002F Interact\n    tm.Send(tea.KeyMsg{Type: tea.KeyDown})\n    tm.Send(tea.KeyMsg{Type: tea.KeyEnter})\n    tm.Type(\"hello\")\n\n    \u002F\u002F Assert intermediate output (polls reader)\n    teatest.WaitFor(t, tm.Output(), func(bts []byte) bool {\n        return bytes.Contains(bts, []byte(\"hello\"))\n    }, teatest.WithDuration(2*time.Second),\n       teatest.WithCheckInterval(100*time.Millisecond))\n\n    \u002F\u002F Quit and assert final state\n    tm.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")})\n    fm := tm.FinalModel(t, teatest.WithFinalTimeout(3*time.Second))\n    m := fm.(myModel)\n    if !m.submitted {\n        t.Error(\"expected submitted\")\n    }\n}\n```\n\n### teatest API reference\n\n| Method | Purpose | Blocks? |\n|--------|---------|---------|\n| `NewTestModel(tb, model, opts...)` | Create & start headless program | No |\n| `tm.Send(msg)` | Inject any `tea.Msg` | No |\n| `tm.Type(s)` | Type string as key events | No |\n| `tm.Output()` | Live output `io.Reader` | No |\n| `tm.FinalOutput(tb, opts...)` | Complete output after quit | Yes |\n| `tm.FinalModel(tb, opts...)` | Final `tea.Model` after quit | Yes |\n| `tm.WaitFinished(tb, opts...)` | Block until program exits | Yes |\n| `WaitFor(tb, reader, cond, opts...)` | Poll reader until condition true | Yes |\n| `RequireEqualOutput(tb, out)` | Golden file comparison | No |\n\n**Always set timeouts** via `WithFinalTimeout` to prevent hanging tests.\n\n---\n\n## CI determinism — the three critical fixes\n\n### 1. Force a fixed color profile\n\nWithout this, golden files from a TrueColor dev terminal will mismatch in CI (no TTY).\n\n```go\n\u002F\u002F v1 — in test init or TestMain\nimport (\n    \"github.com\u002Fcharmbracelet\u002Flipgloss\"\n    \"github.com\u002Fmuesli\u002Ftermenv\"\n)\nfunc init() {\n    lipgloss.SetColorProfile(termenv.Ascii)\n}\n\n\u002F\u002F v2 — per-program\nimport \"github.com\u002Fcharmbracelet\u002Fcolorprofile\"\nprog := tea.NewProgram(model, tea.WithColorProfile(colorprofile.Ascii))\n```\n\nUse `termenv.Ascii` for simplest golden files. Use `termenv.TrueColor` if testing color output.\n\n### 2. Lock terminal dimensions\n\n```go\n\u002F\u002F teatest\nteatest.WithInitialTermSize(80, 24)\n\n\u002F\u002F Direct model tests — send resize before View()\nm, _ := m.Update(tea.WindowSizeMsg{Width: 80, Height: 24})\noutput := m.(myModel).View()\n\n\u002F\u002F v2\ntea.WithWindowSize(80, 24)\n```\n\n### 3. Prevent git from corrupting golden files\n\nAdd to `.gitattributes`:\n\n```\n*.golden -text\ntestdata\u002F** -diff linguist-generated=true\n```\n\nPrevents CRLF normalization and suppresses golden files from GitHub PR diffs.\n\n### Handle non-deterministic elements\n\nSpinners, timestamps, cursor blink, and animations produce varying output. Strategies:\n\n- Freeze spinner frame index to 0 in test setup\n- Inject a clock interface for timestamps, use fixed `time.Time` in tests\n- Disable cursor blink before capture\n- Seed RNGs with constant values\n- For animations, test the final state rather than intermediate frames\n\n---\n\n## Bubble Tea v2 testing options\n\nv2 (`charm.land\u002Fbubbletea\u002Fv2`) adds first-class `ProgramOption` values for testing:\n\n```go\nprog := tea.NewProgram(model,\n    tea.WithWindowSize(80, 24),           \u002F\u002F Fixed dimensions\n    tea.WithInput(nil),                   \u002F\u002F Disable input\n    tea.WithOutput(&buf),                 \u002F\u002F Redirect to buffer\n    tea.WithoutRenderer(),                \u002F\u002F Headless, no rendering\n    tea.WithoutSignals(),                 \u002F\u002F Ignore OS signals\n    tea.WithColorProfile(colorprofile.Ascii), \u002F\u002F Fixed colors\n)\n```\n\nThese replace global `init()` hacks with explicit per-program config.\n\nThe v2 teatest package is at `github.com\u002Fcharmbracelet\u002Fx\u002Fexp\u002Fteatest\u002Fv2`.\n\n---\n\n## Community tools\n\n### knz\u002Fcatwalk — data-driven text-file tests\n\nTest cases as plain text files with input directives:\n\n```\nrun\ntype hello\nkey enter\n----\n-- view:\nYou typed: hello\n```\n\nRun with `-rewrite` to regenerate expected output. Good for testing individual Bubbles components.\n\n**Repo:** `github.com\u002Fknz\u002Fcatwalk`\n\n### Custom direct-model harness (Noteleaf pattern)\n\nDrive `tea.Model` directly without `tea.NewProgram` for single-threaded, faster tests:\n\n```go\ntype TestHarness struct {\n    model tea.Model\n}\n\nfunc (h *TestHarness) SendKey(key tea.KeyType) {\n    var cmd tea.Cmd\n    h.model, cmd = h.model.Update(tea.KeyMsg{Type: key})\n    \u002F\u002F Optionally execute cmd and feed back\n}\n\nfunc (h *TestHarness) WaitForView(contains string, timeout time.Duration) error {\n    deadline := time.Now().Add(timeout)\n    for time.Now().Before(deadline) {\n        if strings.Contains(h.model.View(), contains) {\n            return nil\n        }\n        time.Sleep(10 * time.Millisecond)\n    }\n    return fmt.Errorf(\"timed out waiting for %q\", contains)\n}\n```\n\nLighter than teatest, but doesn't test the terminal rendering pipeline.\n\n---\n\n## Checklist for adding tests to a Bubble Tea app\n\n1. **Set up test infrastructure:**\n   - Create `testdata\u002F` directory for golden files\n   - Add `.gitattributes` entry: `*.golden -text`\n   - Add `init()` or `TestMain` that sets `lipgloss.SetColorProfile(termenv.Ascii)`\n\n2. **Layer 1 — Write table-driven Update tests for:**\n   - Every key binding and its effect on model state\n   - State machine transitions (view switches, mode changes)\n   - Edge cases (empty lists, max cursor, error states)\n   - Commands returned by Update (execute synchronously, assert on msg type)\n   - Custom message handlers (API responses, timer ticks)\n\n3. **Layer 2 — Add golden file tests for key UI states:**\n   - Initial\u002Fwelcome screen\n   - Loading\u002Fspinner state\n   - Error display\n   - Main content with data populated\n   - Empty state\n\n4. **Layer 3 — Write integration tests for critical flows:**\n   - Startup → input → result → quit\n   - Error recovery paths\n   - Multi-step wizards or workflows\n\n5. **CI pipeline:**\n   - Ensure `go test .\u002F...` passes without `-update`\n   - Add `-update` as a manual\u002Fexplicit step only\n   - Consider a CI step that fails if golden files are uncommitted\n","# Bubble Tea Testing\n\nWrite robust, CI-friendly tests for Bubble Tea TUI applications using a three-layer strategy: direct model unit tests, golden file view snapshots, and full-program integration tests via `teatest`.\n\n## Architecture overview\n\nBubble Tea's Elm Architecture (`Init`, `Update`, `View`) makes TUI apps inherently testable. `Update(msg) -> (model, cmd)` is a pure function of state and message — no terminal, program, or event loop needed for most tests.\n\n**Three-layer strategy:**\n\n| Layer | Coverage | Speed | Tool |\n|-------|----------|-------|------|\n| 1. Direct model tests | State transitions, commands, view content | ~ms | Standard `testing` |\n| 2. Golden file snapshots | Visual regression on `View()` output | ~ms | `golden.RequireEqual` |\n| 3. Full integration | End-to-end user flows | ~seconds | `teatest.NewTestModel` |\n\nTarget ratio: **80% Layer 1 \u002F 15% Layer 2 \u002F 5% Layer 3**.\n\n---\n\n## Layer 1: Direct model unit tests\n\n### Constructing test messages\n\nBuild `tea.Msg` values directly — they are plain Go structs:\n\n```go\n\u002F\u002F v1\nqKey   := tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")}\nenter  := tea.KeyMsg{Type: tea.KeyEnter}\nctrlC  := tea.KeyMsg{Type: tea.KeyCtrlC}\ndown   := tea.KeyMsg{Type: tea.KeyDown}\nresize := tea.WindowSizeMsg{Width: 80, Height: 24}\n\n\u002F\u002F v2 renames\nqKey   := tea.KeyPressMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")}\nclick  := tea.MouseClickMsg{X: 10, Y: 5, Button: tea.MouseButtonLeft}\n```\n\n### Table-driven Update tests\n\nThe standard pattern — each case specifies initial state, message, and expected outcome:\n\n```go\nfunc TestUpdate(t *testing.T) {\n    tests := []struct {\n        name       string\n        initial    model\n        msg        tea.Msg\n        wantCursor int\n        wantQuit   bool\n    }{\n        {\n            name:       \"down moves cursor\",\n            initial:    model{cursor: 0, choices: []string{\"a\", \"b\", \"c\"}},\n            msg:        tea.KeyMsg{Type: tea.KeyDown},\n            wantCursor: 1,\n        },\n        {\n            name:       \"cursor stops at bottom\",\n            initial:    model{cursor: 2, choices: []string{\"a\", \"b\", \"c\"}},\n            msg:        tea.KeyMsg{Type: tea.KeyDown},\n            wantCursor: 2,\n        },\n        {\n            name:       \"q triggers quit\",\n            initial:    model{},\n            msg:        tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")},\n            wantQuit:   true,\n        },\n    }\n\n    for _, tt := range tests {\n        t.Run(tt.name, func(t *testing.T) {\n            updated, cmd := tt.initial.Update(tt.msg)\n            m := updated.(model)\n\n            if m.cursor != tt.wantCursor {\n                t.Errorf(\"cursor = %d, want %d\", m.cursor, tt.wantCursor)\n            }\n            if tt.wantQuit {\n                if cmd == nil {\n                    t.Fatal(\"expected quit command\")\n                }\n                if _, ok := cmd().(tea.QuitMsg); !ok {\n                    t.Error(\"quit command did not return QuitMsg\")\n                }\n            }\n        })\n    }\n}\n```\n\n### Testing commands synchronously\n\n`tea.Cmd` is `func() tea.Msg`. Execute it directly and inspect the result:\n\n```go\nfunc TestQuitCommand(t *testing.T) {\n    m := model{}\n    _, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")})\n\n    if cmd == nil {\n        t.Fatal(\"expected quit command\")\n    }\n    msg := cmd() \u002F\u002F execute synchronously\n    if _, ok := msg.(tea.QuitMsg); !ok {\n        t.Errorf(\"expected QuitMsg, got %T\", msg)\n    }\n}\n```\n\n### Mocking I\u002FO dependencies\n\nUse interfaces for anything that does real I\u002FO, inject mocks in tests:\n\n```go\ntype DataFetcher interface {\n    FetchItems() ([]Item, error)\n}\n\ntype model struct {\n    fetcher DataFetcher\n    items   []Item\n}\n\n\u002F\u002F Test mock\ntype mockFetcher struct {\n    items []Item\n    err   error\n}\nfunc (f mockFetcher) FetchItems() ([]Item, error) { return f.items, f.err }\n\nfunc TestFetchSuccess(t *testing.T) {\n    m := model{fetcher: mockFetcher{items: []Item{{Name: \"test\"}}}}\n    cmd := m.fetchCmd()\n    msg := cmd()\n    result, ok := msg.(itemsMsg)\n    if !ok {\n        t.Fatalf(\"expected itemsMsg, got %T\", msg)\n    }\n    if len(result.items) != 1 {\n        t.Errorf(\"expected 1 item, got %d\", len(result.items))\n    }\n}\n```\n\n### Chaining update–command–message cycles\n\nSimulate multi-step flows without a running program:\n\n```go\nfunc TestMultiStepFlow(t *testing.T) {\n    m := tea.Model(initialModel())\n    var cmd tea.Cmd\n\n    \u002F\u002F Step 1: user presses enter\n    m, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})\n\n    \u002F\u002F Step 2: execute the resulting command, feed msg back\n    if cmd != nil {\n        m, cmd = m.Update(cmd())\n    }\n\n    \u002F\u002F Assert final state\n    final := m.(myModel)\n    if final.state != resultView {\n        t.Errorf(\"expected resultView, got %v\", final.state)\n    }\n}\n```\n\n### Testing View output with substring assertions\n\nPrefer substring checks over exact matches — more resilient to styling changes:\n\n```go\nfunc TestViewShowsSelection(t *testing.T) {\n    m := model{\n        cursor:   1,\n        choices:  []string{\"carrots\", \"celery\", \"kohlrabi\"},\n        selected: map[int]struct{}{1: {}},\n    }\n    view := m.View()\n\n    if !strings.Contains(view, \"[x] celery\") {\n        t.Errorf(\"expected selected celery in view:\\n%s\", view)\n    }\n    if !strings.Contains(view, \"[ ] carrots\") {\n        t.Errorf(\"expected unselected carrots in view:\\n%s\", view)\n    }\n}\n```\n\n**Principle:** Assert on intent (flags, indices, content), not styling.\n\n### Testing nested\u002Fcomposed models\n\nTest parent routing and child transitions independently:\n\n```go\nfunc TestParentRoutesToActiveChild(t *testing.T) {\n    parent := newParentModel()\n    updated, _ := parent.Update(tea.WindowSizeMsg{Width: 80, Height: 24})\n    p := updated.(parentModel)\n\n    child := p.list.(listModel)\n    if child.width != 80 {\n        t.Errorf(\"child width = %d, want 80\", child.width)\n    }\n}\n```\n\n---\n\n## Layer 2: Golden file testing\n\n### Packages\n\n| Package | Import | Use case |\n|---------|--------|----------|\n| `golden` | `github.com\u002Fcharmbracelet\u002Fx\u002Fexp\u002Fgolden` | Component-level View snapshots |\n| `teatest` | `github.com\u002Fcharmbracelet\u002Fx\u002Fexp\u002Fteatest` | Full-program output snapshots |\n\n### Component snapshot with `golden.RequireEqual`\n\n```go\nimport \"github.com\u002Fcharmbracelet\u002Fx\u002Fexp\u002Fgolden\"\n\nfunc TestTableRendering(t *testing.T) {\n    tbl := table.New(\n        table.WithColumns(columns),\n        table.WithRows(rows),\n    )\n    \u002F\u002F Compares against testdata\u002FTestTableRendering.golden\n    golden.RequireEqual(t, tbl.View())\n}\n```\n\n`golden.RequireEqual` auto-escapes ANSI codes and uses `go-udiff` for portable diffs.\n\n### Full-program snapshot with `teatest.RequireEqualOutput`\n\n```go\nfunc TestFullOutput(t *testing.T) {\n    tm := teatest.NewTestModel(t, initialModel(),\n        teatest.WithInitialTermSize(80, 24),\n    )\n    tm.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")})\n\n    out, _ := io.ReadAll(tm.FinalOutput(t, teatest.WithFinalTimeout(3*time.Second)))\n    \u002F\u002F Compares against testdata\u002FTestFullOutput.golden\n    teatest.RequireEqualOutput(t, out)\n}\n```\n\n### Golden file workflow\n\n```bash\n# 1. Generate initial golden files\ngo test .\u002F... -update\n\n# 2. Commit them\ngit add testdata\u002F*.golden\n\n# 3. Normal test runs — fails if output differs\ngo test .\u002F...\n\n# 4. After intentional UI changes — regenerate and review diff\ngo test .\u002F... -update\ngit diff testdata\u002F\n```\n\n---\n\n## Layer 3: Full integration with teatest\n\n### Core API\n\n```go\nimport (\n    \"bytes\"\n    \"io\"\n    \"testing\"\n    \"time\"\n\n    tea \"github.com\u002Fcharmbracelet\u002Fbubbletea\"\n    \"github.com\u002Fcharmbracelet\u002Fx\u002Fexp\u002Fteatest\"\n)\n\nfunc TestIntegration(t *testing.T) {\n    tm := teatest.NewTestModel(t, initialModel(),\n        teatest.WithInitialTermSize(80, 24),\n    )\n\n    \u002F\u002F Interact\n    tm.Send(tea.KeyMsg{Type: tea.KeyDown})\n    tm.Send(tea.KeyMsg{Type: tea.KeyEnter})\n    tm.Type(\"hello\")\n\n    \u002F\u002F Assert intermediate output (polls reader)\n    teatest.WaitFor(t, tm.Output(), func(bts []byte) bool {\n        return bytes.Contains(bts, []byte(\"hello\"))\n    }, teatest.WithDuration(2*time.Second),\n       teatest.WithCheckInterval(100*time.Millisecond))\n\n    \u002F\u002F Quit and assert final state\n    tm.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(\"q\")})\n    fm := tm.FinalModel(t, teatest.WithFinalTimeout(3*time.Second))\n    m := fm.(myModel)\n    if !m.submitted {\n        t.Error(\"expected submitted\")\n    }\n}\n```\n\n### teatest API reference\n\n| Method | Purpose | Blocks? |\n|--------|---------|---------|\n| `NewTestModel(tb, model, opts...)` | Create & start headless program | No |\n| `tm.Send(msg)` | Inject any `tea.Msg` | No |\n| `tm.Type(s)` | Type string as key events | No |\n| `tm.Output()` | Live output `io.Reader` | No |\n| `tm.FinalOutput(tb, opts...)` | Complete output after quit | Yes |\n| `tm.FinalModel(tb, opts...)` | Final `tea.Model` after quit | Yes |\n| `tm.WaitFinished(tb, opts...)` | Block until program exits | Yes |\n| `WaitFor(tb, reader, cond, opts...)` | Poll reader until condition true | Yes |\n| `RequireEqualOutput(tb, out)` | Golden file comparison | No |\n\n**Always set timeouts** via `WithFinalTimeout` to prevent hanging tests.\n\n---\n\n## CI determinism — the three critical fixes\n\n### 1. Force a fixed color profile\n\nWithout this, golden files from a TrueColor dev terminal will mismatch in CI (no TTY).\n\n```go\n\u002F\u002F v1 — in test init or TestMain\nimport (\n    \"github.com\u002Fcharmbracelet\u002Flipgloss\"\n    \"github.com\u002Fmuesli\u002Ftermenv\"\n)\nfunc init() {\n    lipgloss.SetColorProfile(termenv.Ascii)\n}\n\n\u002F\u002F v2 — per-program\nimport \"github.com\u002Fcharmbracelet\u002Fcolorprofile\"\nprog := tea.NewProgram(model, tea.WithColorProfile(colorprofile.Ascii))\n```\n\nUse `termenv.Ascii` for simplest golden files. Use `termenv.TrueColor` if testing color output.\n\n### 2. Lock terminal dimensions\n\n```go\n\u002F\u002F teatest\nteatest.WithInitialTermSize(80, 24)\n\n\u002F\u002F Direct model tests — send resize before View()\nm, _ := m.Update(tea.WindowSizeMsg{Width: 80, Height: 24})\noutput := m.(myModel).View()\n\n\u002F\u002F v2\ntea.WithWindowSize(80, 24)\n```\n\n### 3. Prevent git from corrupting golden files\n\nAdd to `.gitattributes`:\n\n```\n*.golden -text\ntestdata\u002F** -diff linguist-generated=true\n```\n\nPrevents CRLF normalization and suppresses golden files from GitHub PR diffs.\n\n### Handle non-deterministic elements\n\nSpinners, timestamps, cursor blink, and animations produce varying output. Strategies:\n\n- Freeze spinner frame index to 0 in test setup\n- Inject a clock interface for timestamps, use fixed `time.Time` in tests\n- Disable cursor blink before capture\n- Seed RNGs with constant values\n- For animations, test the final state rather than intermediate frames\n\n---\n\n## Bubble Tea v2 testing options\n\nv2 (`charm.land\u002Fbubbletea\u002Fv2`) adds first-class `ProgramOption` values for testing:\n\n```go\nprog := tea.NewProgram(model,\n    tea.WithWindowSize(80, 24),           \u002F\u002F Fixed dimensions\n    tea.WithInput(nil),                   \u002F\u002F Disable input\n    tea.WithOutput(&buf),                 \u002F\u002F Redirect to buffer\n    tea.WithoutRenderer(),                \u002F\u002F Headless, no rendering\n    tea.WithoutSignals(),                 \u002F\u002F Ignore OS signals\n    tea.WithColorProfile(colorprofile.Ascii), \u002F\u002F Fixed colors\n)\n```\n\nThese replace global `init()` hacks with explicit per-program config.\n\nThe v2 teatest package is at `github.com\u002Fcharmbracelet\u002Fx\u002Fexp\u002Fteatest\u002Fv2`.\n\n---\n\n## Community tools\n\n### knz\u002Fcatwalk — data-driven text-file tests\n\nTest cases as plain text files with input directives:\n\n```\nrun\ntype hello\nkey enter\n----\n-- view:\nYou typed: hello\n```\n\nRun with `-rewrite` to regenerate expected output. Good for testing individual Bubbles components.\n\n**Repo:** `github.com\u002Fknz\u002Fcatwalk`\n\n### Custom direct-model harness (Noteleaf pattern)\n\nDrive `tea.Model` directly without `tea.NewProgram` for single-threaded, faster tests:\n\n```go\ntype TestHarness struct {\n    model tea.Model\n}\n\nfunc (h *TestHarness) SendKey(key tea.KeyType) {\n    var cmd tea.Cmd\n    h.model, cmd = h.model.Update(tea.KeyMsg{Type: key})\n    \u002F\u002F Optionally execute cmd and feed back\n}\n\nfunc (h *TestHarness) WaitForView(contains string, timeout time.Duration) error {\n    deadline := time.Now().Add(timeout)\n    for time.Now().Before(deadline) {\n        if strings.Contains(h.model.View(), contains) {\n            return nil\n        }\n        time.Sleep(10 * time.Millisecond)\n    }\n    return fmt.Errorf(\"timed out waiting for %q\", contains)\n}\n```\n\nLighter than teatest, but doesn't test the terminal rendering pipeline.\n\n---\n\n## Checklist for adding tests to a Bubble Tea app\n\n1. **Set up test infrastructure:**\n   - Create `testdata\u002F` directory for golden files\n   - Add `.gitattributes` entry: `*.golden -text`\n   - Add `init()` or `TestMain` that sets `lipgloss.SetColorProfile(termenv.Ascii)`\n\n2. **Layer 1 — Write table-driven Update tests for:**\n   - Every key binding and its effect on model state\n   - State machine transitions (view switches, mode changes)\n   - Edge cases (empty lists, max cursor, error states)\n   - Commands returned by Update (execute synchronously, assert on msg type)\n   - Custom message handlers (API responses, timer ticks)\n\n3. **Layer 2 — Add golden file tests for key UI states:**\n   - Initial\u002Fwelcome screen\n   - Loading\u002Fspinner state\n   - Error display\n   - Main content with data populated\n   - Empty state\n\n4. **Layer 3 — Write integration tests for critical flows:**\n   - Startup → input → result → quit\n   - Error recovery paths\n   - Multi-step wizards or workflows\n\n5. **CI pipeline:**\n   - Ensure `go test .\u002F...` passes without `-update`\n   - Add `-update` as a manual\u002Fexplicit step only\n   - Consider a CI step that fails if golden files are uncommitted\n",{"name":5,"description":7},"main","bcfcd42255878c3d40e545abcdeb2520b6d31a52",".pi-go\u002Fskills\u002Fbubbletea-testing",34,"https:\u002F\u002Fgithub.com\u002Fdimetron\u002Fpi-go","https:\u002F\u002Fpi-go.sh","https:\u002F\u002Fgithub.com\u002Fdimetron","🎸💻 🚧🦞","2026-11-15 03:48:24",{"source":8,"skillName":5,"commands":60,"prompt":70,"zipAvailable":71},[61,64,67],{"tool":62,"command":63},"npx","npx skills add dimetron\u002Fpi-go --skill bubbletea-testing",{"tool":65,"command":66},"bunx","bunx skills add dimetron\u002Fpi-go --skill bubbletea-testing",{"tool":68,"command":69},"pnpm","pnpm dlx skills add dimetron\u002Fpi-go --skill bubbletea-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdimetron\u002Fpi-go\u002Fblob\u002Fmain\u002F.pi-go\u002Fskills\u002Fbubbletea-testing\u002FSKILL.md",true,[73],{"path":74,"resourceType":75,"resourceTypeDesc":76,"sizeBytes":77,"sourceHtmlUrl":78},"_AIWF_IMPORT.json","REFERENCE","参考文档",309,"https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fgithub_imports\u002Fdoc-coauthoring\u002F_AIWF_IMPORT.json",[80,104,127,145,160,180],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":45},"01M70SJ3216A0Y2NXYJJ2MVER0","verify-session-flow","Formally verify the interactive session flow before or after changing it. Use when editing internal\u002Ftui\u002Ftui.go's handleKey, handleInterruptKey, handleInputSubmit, ctrlCCount or quitting, internal\u002Ftui\u002Fagent_loop.go's enqueuePrompt, submit, steerPrompt, cancelAgent or handleAgentDone, or the deferred-init splash — or when a user reports that Ctrl+C quit on the first press, that Esc did not stop a turn or a goal loop, that a queued prompt was lost when they canceled, or that the TUI hung on a spinner nothing could clear.","https:\u002F\u002Fgithub.com\u002Fdimetron\u002Fpi-go\u002Fblob\u002Fmain\u002Finternal\u002Fextension\u002Fbundled_skills\u002Fverify-session-flow\u002FSKILL.md",[],[87,88,89,90,91,92,39,32,93,94,95,96,97,98,99,100,101,41,102,103],"session","verify session flow","verify","flow","submit","editing","loop","prompt","when","interactive","reports","first","goal","CTRL","clear","spinner","tui",{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":45},"01M70SJ02CTB40V2VFGAF80SBG","verify-run-pipeline","Formally verify the \u002Frun phase machine before or after changing it. Use when editing internal\u002Ftui\u002Frun.go's phase transitions (handleRunAgentDone, runGates result handling, verifyRunComplete, retryRun, reportGateHang, merge), internal\u002Fsop\u002Fverdict.go's Passed, or the checklist refresh — or when a run merged work it should not have, retried a hung gate, lost a cycle at the retry budget, or merged on a stale PASS.","https:\u002F\u002Fgithub.com\u002Fdimetron\u002Fpi-go\u002Fblob\u002Fmain\u002Finternal\u002Fextension\u002Fbundled_skills\u002Fverify-run-pipeline\u002FSKILL.md",[],[111,112,89,113,114,115,92,116,117,118,32,95,119,120,121,122,123,124,125,126],"pipeline","verify run pipeline","run","run pipeline","retry","cycle","run phase","machine","phase","refresh","work","verdict","transitions","result","merge","sop",{"skillNo":128,"name":129,"nameZh":6,"description":130,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":131,"categories":132,"keywords":133,"publishedAt":45},"01M70SHWJV9N3PQWRAMCQE9C2E","verify-history-rewrite","Formally verify the session-history rewrite path before or after changing it. Use when editing internal\u002Fsession\u002Fautocompact.go, internal\u002Fsession\u002Fcompaction*.go, internal\u002Fsession\u002Fstore.go's Compact\u002FClearEvents\u002FrewriteEvents, internal\u002Fagent\u002Fagent.go's Run\u002FRunStreaming\u002FrunPreTurn, or internal\u002Ftui\u002Fcommands.go's clearConversation\u002FclearSessionContext and the context gauge — or when a turn is canceled mid-flight, a tool call and its result get separated, a session's history disappears while the agent is still working, or the model is sent a tool result whose call was compacted away.","https:\u002F\u002Fgithub.com\u002Fdimetron\u002Fpi-go\u002Fblob\u002Fmain\u002Finternal\u002Fextension\u002Fbundled_skills\u002Fverify-history-rewrite\u002FSKILL.md",[],[134,135,136,89,137,138,92,87,139,140,32,141,95,142,143,124,113,144,41,103],"history","rewrite","verify history rewrite","get","model","tool","call","compact","store","gauge","commands",{"skillNo":146,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":149,"categories":150,"keywords":151,"publishedAt":45},"01M70SHSJ5A2XV5SXBXM96RH7P","verify-goal-loop","Formally verify the \u002Fgoal automatic loop before or after changing it. Use when editing internal\u002Ftui\u002Fgoal.go, internal\u002Ftui\u002Fagent_loop.go's handleAgentDone\u002FcancelAgent\u002FsteerPrompt, or internal\u002Ftools\u002Fgoal.go's GoalController — or when a goal loop will not stop, stops one cycle early, closes a goal that is not met, or restarts a goal you finished.","https:\u002F\u002Fgithub.com\u002Fdimetron\u002Fpi-go\u002Fblob\u002Fmain\u002Finternal\u002Fextension\u002Fbundled_skills\u002Fverify-goal-loop\u002FSKILL.md",[],[93,152,153,89,99,154,92,116,32,95,155,156,41,103,157,158,159],"verify goal loop","verify goal","goal loop","you","automatic","Tools","it","stop",{"skillNo":161,"name":162,"nameZh":6,"description":163,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":164,"categories":165,"keywords":166,"publishedAt":45},"01M70SHPYN1AS6D6RJ8HN270RZ","verify-agent-lifecycle","Formally verify the subagent lifecycle before or after changing it. Use when editing internal\u002Fsubagent\u002Forchestrator.go's Spawn, trackAgent, forwardAgentEvents, terminalStatus, Cancel, ShutdownWithTimeout or evictCompletedAgentsLocked, or internal\u002Fsubagent\u002Fpool.go — or when a canceled agent is reported as failed, an agent vanishes from the list with no verdict, the orchestrator panics on a pool release, or an agent can be canceled twice.","https:\u002F\u002Fgithub.com\u002Fdimetron\u002Fpi-go\u002Fblob\u002Fmain\u002Finternal\u002Fextension\u002Fbundled_skills\u002Fverify-agent-lifecycle\u002FSKILL.md",[],[167,168,169,89,170,92,32,95,171,172,173,174,122,175,176,177,178,41,158,179],"lifecycle","verify agent lifecycle","agent lifecycle","as","cancel","subagent","can","with","orchestrator","spawn","release","list","pool",{"skillNo":181,"name":182,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":183,"categories":184,"keywords":185,"publishedAt":45},"01M6E37WZM8ZF36DRYQGZDGP7M","test-new-skill","https:\u002F\u002Fgithub.com\u002Fdimetron\u002Fpi-go\u002Fblob\u002Fmain\u002Finternal\u002Ftui\u002F.pi-go\u002Fskills\u002Ftest-new-skill\u002FSKILL.md",[],[186,187,188,189],"test","new skill","test new skill","new"]