使用 /add-test Skill 为 vscode-gitlens 生成单元测试与 E2E 测试:完整实战指南
开发工具版本控制【免费下载链接】vscode-gitlensSupercharge Git inside VS Code and unlock untapped knowledge within each repository — Visualize code authorship at a glance via Git blame annotations and CodeLens, seamlessly navigate and explore Git repositories, gain valuable insights via rich visualizations and powerful comparison commands, and so much more项目地址https://gitcode.com/gh_mirrors/vs/vscode-gitlens点击查看免费下载导读本文基于 vscode-gitlens 仓库内置的/add-testClaude Code Skill 文档系统讲解如何为既有代码自动生成单元测试与 Playwright E2E 测试包括命令语法、标准测试模板、GitFixture 仓库构造方法、Webview 定位与 Pro 功能模拟等关键能力。读完本文你将掌握该 Skill 的完整调用方式理解 GitLens 仓库测试基础设施tests/e2e/baseTest.ts、tests/e2e/fixtures/git.ts、tests/e2e/playwright.config.ts的底层原理并能独立编写、运行和调试符合仓库规范的测试用例。一、Skill 概览与适用场景/add-test是仓库中面向 AI 编程助手Claude Code 等的专用 Skill定义于 .claude/skills/add-test/SKILL.md其description字段明确其职责Generate unit or E2E test files for existing code——为已有代码生成单元测试或 E2E 测试文件。在 GitLens 这种体量的仓库中测试分为两大体系Skill 也据此分为两种模式模式目标文件位置技术栈覆盖重点unit默认src/path/__tests__/file.test.tsNode 内置assert Mocha 风格suite/test纯函数、类方法、异步逻辑、错误分支e2etests/e2e/specs/feature.test.tsPlaywright Electron真实 VS Code 中的 UI 呈现、交互、导航、Pro 门槛两种模式的测试分别通过pnpm run test单元与pnpm run test:e2eE2E运行对应脚本定义在 package.json。二、命令用法Skill 通过斜杠命令触发完整语法为/add-test [type] [target]type——unit默认值或e2e决定生成哪种测试target—— 要测试的文件路径或功能名称feature name。典型调用示例/add-test unit src/git/utils/emoji.ts # 为指定文件生成单元测试 /add-test e2e commit-graph # 为 Commit Graph 功能生成 E2E 测试 /add-test graphRowActions # 省略 type默认为 unit三、单元测试模板详解Skill 会为src/path/__tests__/file.test.ts生成基于 Mocha 风格suite/test的测试骨架使用 Node 内置的assert模块不依赖额外断言库import * as assert from assert; import { functionToTest } from ../file.js; suite(FeatureName Test Suite, () { suite(functionName, () { test(should handle normal input, () { const result functionToTest(input); assert.strictEqual(result, expected); }); test(should handle edge case, () { const result functionToTest(); assert.strictEqual(result, undefined); }); test(should throw on invalid input, () { assert.throws(() functionToTest(null), /error message/); }); }); suite(async function, () { test(should resolve with data, async () { const result await asyncFunction(); assert.deepStrictEqual(result, { key: value }); }); }); });几个值得注意的仓库规范点导入使用.js后缀仓库启用了require-js-extension等 ESLint 规则见 scripts/eslint-rules/require-js-extension.mjsESM 风格导入必须显式携带.js扩展名suite嵌套外层 suite 对应被测模块内层 suite 对应具体函数test描述使用 should ... 行为化命名推荐的断言方法SKILL 明确规定assert.strictEqual()、assert.deepStrictEqual()、assert.ok()、assert.throws()。这一模板与仓库真实单元测试完全一致。以 src/tests/errors.test.ts 为例真实测试同样采用suite(getPresentableErrorMessage, () { test(...) })结构并用assert.strictEqual/assert.deepStrictEqual断言同时展示了如何通过Object.defineProperty模拟localizedMessagegetter、用try/finally包裹l10n.config隔离全局状态等进阶技巧——这些都可以作为边界条件 状态隔离的范式参考。Mock 支持sinon当被测代码依赖外部模块或异步副作用时模板内置了sinonsandbox 的标准用法import * as sinon from sinon; let sandbox: sinon.SinonSandbox; setup(() { sandbox sinon.createSandbox(); }); teardown(() { sandbox.restore(); });在setup中创建 sandbox、teardown中restore保证每个用例之间的 stub/spy 状态互不泄漏——这是仓库单元测试的通用隔离约定。单元测试编写五步流程SKILL 规定的编写流程为先读目标文件弄清其导出exports确定要覆盖的函数与类按需创建__tests__/目录若不存在覆盖四类场景正常路径、边界情况空字符串 /null/undefined、错误条件、异步操作按上表选择断言方法运行验证见第七节。四、E2E 测试模板详解E2E 模式生成tests/e2e/specs/feature.test.ts基于 Playwright 的test.extend自定义 fixture 机制在vscodeOptions中通过setup钩子完成 Git 仓库的准备import { test as base, createTmpDir, expect, GitFixture, MaxTimeout } from ../baseTest.js; const test base.extend({ vscodeOptions: [ { vscodeVersion: process.env.VSCODE_VERSION ?? stable, setup: async () { const repoDir await createTmpDir(); const git new GitFixture(repoDir); await git.init(); await git.commit(Initial commit, README.md, # Test); return repoDir; }, }, { scope: worker }, ], }); test.describe(Feature Name, () { test.describe.configure({ mode: serial }); test.afterEach(async ({ vscode }) { await vscode.gitlens.resetUI(); }); test(should display feature correctly, async ({ vscode }) { await vscode.gitlens.openGitLensSidebar(); await expect(vscode.page.getByRole(heading)).toContainText(Expected); }); });模板中每个元素都有明确用途vscodeVersion通过环境变量VSCODE_VERSION控制编辑器版本stable为默认设为insiders即对应pnpm run test:e2e:insiders脚本见 package.json{ scope: worker }fixture 在 worker 级共享整个 worker 只启动一次编辑器多个测试复用createTmpDir()/GitFixture为每个测试创建独立临时仓库test.describe.configure({ mode: serial })串行执行保证共享 Git 状态的测试之间顺序确定vscode.gitlens.resetUI()afterEach恢复 UI 状态避免污染后续用例。E2E 断言统一使用 Playwright 的expectexpect(locator).toBeVisible()、.toContainText()、.toHaveCount()等这是 Playwright 内置的自动重试断言天然适配异步 UI 场景。底层 fixture 基础设施模板导入的baseTest来自 tests/e2e/baseTest.ts其中定义了多个关键设施超时常量baseTest.tsMaxTimeout 10000、DefaultTimeout 2000、ShortTimeout 500模板中的MaxTimeout即来源于此expect与GitFixture的再导出使所有 spec 可以统一从../baseTest.js导入编辑器无关的 GitLens 激活等待waitForGitLensActivation通过vscode.extensions.getExtension(eamodio.gitlens)?.isActive轮询扩展宿主是否激活不依赖任何 workbench UI因此可跨 VS Code 及 Cursor 等 fork 工作assertWorkbenchReachable针对 Cursor.onboarding-v2-overlay与 Kirokiro-sign-in-page等全屏登录墙 fork 做快速失败检测避免每个 UI 用例烧满 30 秒点击超时Xvfb 支持Linux 无显示环境下自动拉起 XvfbDISPLAY:99使 E2E 可在 WSL/SSH 的 headless 环境运行。Playwright 全局配置playwright.config.ts 中与 spec 编写直接相关的默认行为包括actionTimeout: 30000限制单个动作等待避免通知浮层遮挡按钮时烧完整个测试预算、trace: on-first-retry与video: on-first-retry首次重试时记录 trace 与视频便于失败排查、screenshot: only-on-failure、timeout: 60000、CI 环境retries: 2、fullyParallel: true以及通过grepInvert默认排除performance与fork 的no-fork标记用例。五、E2E 测试编写指南MCP 先行的选择器验证SKILL 对 E2E 编写给出的核心纪律是不要猜测选择器Dont guess at selectors用 MCP 服务器实地验证。完整流程为先用 MCP 探索——通过/live-inspect启动 VS Code 并发现正确的选择器。文档给出了一套可复用的工具调用序列launch {} # 启动 VS Code 实例 execute_command { command: gitlens.showGraphView } # 执行命令打开视图 aria_snapshot {} # 查看所有 UI 元素与 role inspect_dom { selector: h1, in_webview: true } # 检查 webview 内容 screenshot {} # 视觉确认确定测试所需 Git 状态——需要哪些 commits、branches、tags用 GitFixture 搭建 setup使用 MCP 发现的选择器编写测试用 MCP 验证——在定稿前手动走一遍测试场景确认断言成立inspect_dom验证元素文本/可见性evaluate检查扩展运行时状态screenshot目视确认 UI覆盖范围UI 呈现、用户交互、导航、错误状态、Pro 与 Community 功能门槛断言风格toBeVisible()/toContainText()/toHaveCount()。这一先探索、后断言的做法与真实 spec 高度一致。例如 tests/e2e/specs/graphHeader.test.ts 中测试通过button.action-button[aria-label...]与[href*command:id]定位 header 按钮与命令链接并专门用aria-label而非可见文本定位 WIP 行——注释graphHeader.test.ts说明这是因为详情面板会渲染同名字符串、窄宽度下可见标签会退化为短形式而 aria-label 由commit.message构建、任何宽度下都不变。这类选择器洞察正是 MCP 实测才能沉淀的经验。六、Webview 内容与 Pro 功能门槛6.1 获取 Webview FrameLocatorGitLens 的 Commit Graph、Inspect 等核心视图是 webview。SKILL 提供getGitLensWebview(title, purpose)方法获取FrameLocatorconst webview await vscode.gitlens.getGitLensWebview(Graph, webviewView); await expect(webview!.locator(h1)).toContainText(Expected heading); await expect(webview!.getByRole(button, { name: /Try Pro/i })).toBeVisible();可用的 webview 标题Graph、Graph Details、Inspect、Visual File History、Interactive Rebasepurpose取值webviewView侧边栏/面板、webviewPanel编辑器标签页、customEditor自定义编辑器如 Interactive Rebase。该方法在 tests/e2e/pageObjects/gitLensPage.ts 中的实现值得了解它先按iframe.webview[src*extensionIdeamodio.gitlens]webviewView时额外带purpose过滤枚举 iframe再进入iframe#active-frame[title*${title}]做精确标题匹配——用title*只是粗筛真正接受的是actualTitle title或带分支后缀的形式如Interactive Rebase (main)从而避免 Graph 同时误匹配 Commit Graph 与 Commit Graph Inspect。另外实现中针对WebviewView 偶发丢失 purpose 属性的 VS Code 已知问题做了隔次轮询回退说明该辅助方法已对真实环境中的不确定性做了充分容错。6.2 Pro 功能门槛模拟E2E 测试需要覆盖 Pro 与 Community 的功能差异。SKILL 提供订阅模拟方案通过using声明实现作用域自动还原// Simulate Pro subscription for the test using _ await vscode.gitlens.startSubscriptionSimulation({ state: 6 /* SubscriptionState.Paid */, planId: pro, }); // Pro features now accessible — auto-reverts when scope exits其底层实现gitLensPage.ts是执行gitlens.plus.simulate.subscription命令等待订阅变更事件传播并返回同时实现Symbol.dispose同步、静默吞掉未处理 rejection 以防拖垮 worker与Symbol.asyncDispose可 await 的还原路径的双重 disposer——这正是using语法能够作用域退出即自动还原的原因。注意state用数字 6 对应SubscriptionState.PaidplanId为pro。七、GitFixture 方法速查E2E setup 阶段构造 Git 仓库的完整方法清单SKILL 收录签名与真实实现 tests/e2e/fixtures/git.ts 一致await git.init() // git init -b main 配置 user 初始提交 await git.commit(message, fileName, content) // 写文件、add、commit默认 test-file.txt / content await git.branch(name) // 创建分支 await git.checkout(name, create?) // 切换分支createtrue 时 -b 新建 await git.tag(name, { message?, ref? }) // 打标签message 存在时生成 annotated tag await git.stash(message?) // git stash push [-m] await git.worktree(path, branch) // git worktree add await git.addRemote(name, url) // git remote add await git.merge(branch, message?) // 合并分支noFF 可选SKILL 之外实现类还提供了一批实战中高频使用的方法均可按需调用deleteBranch(name, force true)、clean()、config(key, value)--local作用域写仓库配置createFile/stage/reset(ref, mode)/setUpstream/createRemoteBranch无真实远端时构造上游跟踪场景状态查询getStatusLines()、getShortSha()/getSha()、getCommitMessage()、getCurrentBranch()冲突/合并场景mergeAbort()、rebaseAbort()、isMergeInProgress()、isRebaseInProgress()、getUnmergedPaths()、cleanupRebaseState()交互式 rebaserebaseInteractive(onto, options)与startRebaseInteractiveWithWaitEditor(...)配合 scripts/tests/waitEditor.mjs 控制 rebase 完成时机返回waitForTodoFile/signalEditorDone/signalEditorAbort助手worktree 清理removeWorktree(path)--force、pruneWorktrees()。两个实现级细节对编写稳定测试至关重要确定性commit支持options.date固定GIT_AUTHOR_DATE/GIT_COMMITTER_DATEgit.ts注释明确指出同一秒内创建的提交排序任意、会导致图行位置漂移——需要图行顺序确定的测试务必指定日期环境隔离底层git()方法git.ts为每个子进程设置GIT_CONFIG_GLOBAL/dev/null与GIT_CONFIG_SYSTEM/dev/null避免开发者的全局merge.ffonly、rerere.enabled、全局hooksPath等配置静默改变命令行为——这保证了 fixture 仓库在任何机器与 CI 上行为一致测试只依赖方法显式设置的配置。八、运行测试与结果解读SKILL 给出的两条核心命令pnpm run test -- --grep FeatureName # 单元测试按名称过滤 pnpm run test:e2e -- tests/e2e/specs/file.test.ts # E2E 测试按文件过滤结合 docs/testing.md 的补充有几点必须注意8.1 运行前置条件确保扩展已构建pnpm run build或保持pnpm run watch运行E2E 前需执行pnpm run bundle:e2e或使用 watch 模式——E2E 测试依赖打包产物单元测试可单独构建pnpm run build:tests。8.2 传递 Playwright 选项的正确姿势docs/testing.md特别强调了一个坑不要用pnpm run test:e2e -- option传 Playwright 选项因为 pnpm 会把字面的--原样转发给 Playwright后者将其视为位置参数文件过滤而静默忽略选项——这正是 CI 直接调用pnpm exec playwright的原因。正确做法是pnpm exec playwright test -c tests/e2e/playwright.config.ts tests/e2e/specs/quickWizard.test.ts pnpm exec playwright test -c tests/e2e/playwright.config.ts --grep wizard pnpm exec playwright test -c tests/e2e/playwright.config.ts --headed # 有头模式调试 pnpm exec playwright test -c tests/e2e/playwright.config.ts --projectvscode WINDSURF_E2E_PATH/path/to/windsurf pnpm exec playwright test -c tests/e2e/playwright.config.ts --projectwindsurf8.3 标记tag约定no-fork仅标注 fork 编辑器缺少对应 UI 表面导致无法驱动的真实不兼容禁止用于功能失败fork 项目以grepInvert: /no-fork/排除而vscode项目全量运行performance浏览器性能 spec 专属标记默认从普通 E2E 运行排除须显式--grep performance或直接按graphPerformance.test.ts文件路径选中、或设置GITLENS_E2E_PERFORMANCE1才会运行cli-insidersGK CLI insiders 通道用例需GL_E2E_CLI_INSIDERS1环境变量才会执行见 docs/testing.md。8.4 输出解读与调试输出中PASS表示通过FAIL表示失败——重点看Error:、AssertionError:、expect(行获取失败详情E2E 失败时截图与 trace 输出在tests/e2e/test-results/配置中outputDir实际为../../out/test-results常用调试命令--reporterlist获取详细输出、--trace on --grep test name运行单测并记录完整 trace、pnpm run check先排除 TypeScript 类型错误。8.5 调试失败的原则docs/testing.md末尾的 AI 助手指南给出了一个明确的工程原则调试失败时不要为了让测试通过而简化或篡改测试意图——应当调查并理解失败的根因直接解决根因若无法解决向用户提出 issue。这与该 Skill 的初衷一致测试生成的质量目标是真实覆盖代码行为而非制造绿灯。九、与仓库测试结构的对应关系/add-test生成的两个路径分别对应仓库的两套测试体系详见 docs/testing.md单元测试与被测源码同目录的__tests__/目录命名file.test.ts。仓库现有实例包括 src/tests/cacheProvider.test.ts、src/tests/errors.test.ts、src/tests/resourceUsage.test.ts以及src/git/__tests__/、src/commands/__tests__/等各子模块下的测试E2E 测试集中在 tests/e2e/specs/配套基础设施位于 tests/e2e/fixtures/git.ts、mcp.ts、vscodeEvaluator.ts、tests/e2e/pageObjects/gitLensPage.ts、vscodePage.ts及 components 子目录与 tests/e2e/helpers/mcpHelper.ts。仓库现有 20 个 spec如graphHeader.test.ts、quickWizard.test.ts、rebase.test.ts、treeView.test.ts等是研读真实 E2E 写法的第一手资料。十、总结一份可复用的测试生成工作流/add-testSkill 的核心价值在于把 GitLens 仓库的测试规范固化为可执行流程确定模式纯逻辑用unitassert sinonUI 与交互用e2ePlaywright MCP 探索单元测试读导出 → 建__tests__/→ 覆盖正常/边界/错误/异步四类场景 → 运行pnpm run test -- --grep验证E2E 测试MCP 实测选择器 → 规划 Git 状态 → GitFixture 搭建 → 编写断言 → 处理 Webview 与 Pro 门槛 → 用pnpm exec playwright按文件/按 grep 运行验证善用基础设施确定性日期提交、全局 git 配置隔离、getGitLensWebview的标题精确匹配、startSubscriptionSimulation的自动还原都是保证测试稳定与可复现的关键。按此工作流生成的测试能够与仓库现有测试体系无缝衔接直接进入 CI 矩阵运行。赞分享开发工具版本控制【免费下载链接】vscode-gitlensSupercharge Git inside VS Code and unlock untapped knowledge within each repository — Visualize code authorship at a glance via Git blame annotations and CodeLens, seamlessly navigate and explore Git repositories, gain valuable insights via rich visualizations and powerful comparison commands, and so much more项目地址https://gitcode.com/gh_mirrors/vs/vscode-gitlens点击查看免费下载相关推荐GSD「add-tests」命令实战为已完成阶段自动生成并提交单元测试与 E2E 测试GSD「add tests」命令实战为已完成阶段自动生成并提交单元测试与 E2E 测试 导读 /gsd:add tests 是 get shit doneG人工智能AI 应用提示工程开发工具工作流自动化AI AgentSuper Productivity 多语言翻译指南基于 en.json 的 i18n 工作流与脚本化管理Super Productivity 多语言翻译指南基于 en.json 的 i18n 工作流与脚本化管理 Super Productivity 的国际化i开发工具版本控制OpenCore Legacy Patcher 安装指南老款 Intel Mac 跑新 macOSOpenCore Legacy Patcher 安装指南老款 Intel Mac 跑新 macOS OpenCore Legacy PatcherOCLP操作系统固件驱动开发上一篇Obsidian Kanban图片添加全攻略让看板可视化效果翻倍提升下一篇视频字幕智能化自动生成技术的革命性突破创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考