You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为VS Code Test Explorer视图的TestItem定义条件内联菜单?

解决Test Explorer自定义菜单命令的显示问题

问题核心在于:Test Explorer视图的上下文变量和VS Code普通资源的上下文不通用,你使用的resourceExtname这类键仅适用于编辑器或文件资源相关场景,对TestItem完全无效。要实现按TestItem类型显示菜单,得用TestItem专属的上下文机制。

步骤1:给TestItem设置自定义上下文标识

在创建或更新TestItem的代码中,通过contextValue属性给不同类型的测试项打上专属标记,比如JSON类型的测试项:

// 示例:创建一个JSON类型的测试项
const jsonTestItem = vscode.tests.createTestItem(
  'json-test-1',
  'JSON格式测试',
  vscode.Uri.file('/path/to/your/test.json')
);
// 给该测试项添加自定义上下文值
jsonTestItem.contextValue = 'jsonTest';
// 将测试项加入测试集合
testCollection.add(jsonTestItem);

你可以根据测试项的实际类型,设置不同的contextValue,比如pythonTest、integrationTest等。

步骤2:在package.json中使用自定义上下文判断

修改原有menus配置,把when条件替换为testingItemContext,匹配你给TestItem设置的标识:

{
  "contributes": {
    "commands": [
      {
        "command": "runTest",
        "title": "Run Test",
        "icon": {
          "light": "images/light/play-circle.svg",
          "dark": "images/dark/play-circle.svg"
        }
      }
    ],
    "menus": {
      "testing/item/context": [
        {
          "command": "runTest",
          "group": "inline",
          // 匹配TestItem的contextValue
          "when": "testingItemContext == jsonTest"
        }
      ]
    }
  }
}

额外说明

  • 右键菜单和内联工具栏的逻辑完全一致,只要when条件匹配testingItemContext就能正确显示对应命令。
  • 如果需要更复杂的显示逻辑,可以组合多个Test Explorer专属上下文键,比如:
    "when": "testingItemContext == jsonTest && testing:hasResults"
    
    这样只有带有测试结果的JSON测试项才会显示该命令。

内容的提问来源于stack exchange,提问作者smeep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 13:55:22