AGENT SKILL

后端单元测试编写

backend-tests

用于编写 test/unit-tests/backend/*.test.ts 下的单元测试,这些测试在 Node 中运行,使用 Mocha+Chai 且不依赖 VS Code API。适用于纯逻辑:解析器、辅助函数、环境合并。触发词:"backend test"、"unit test"、"mocha test without vscode"。

适用职业测试工程师
License 许可
MIT
最近更新
2026-11-11
Stars
★ 1.7k
Forks
559

01 前言 Front Matter

name
backend-tests
description
Use when writing unit tests under test/unit-tests/backend/*.test.ts that run in Node with Mocha+Chai and no VS Code API. For pure logic: parsers, helpers, env merging. Triggers: "backend test", "unit test", "mocha test without vscode".

03 SKILL.md 正文

Writing Backend Tests

Recipe for adding backend (unit) tests that run without VS Code.

When to use backend tests

Use backend tests for pure logic that has no VS Code UI interaction. They are the fastest feedback loop — no Extension Host, no display server, just Node + Mocha.

Good candidates: string manipulation, path logic, parsers, encoding, variable expansion, data-structure helpers, environment merging.

Not suitable for: anything that calls vscode.window.*, vscode.workspace.* beyond getConfiguration(), or depends on an active editor.


File location

test/unit-tests/backend/<name>.test.ts

Import strategy — decision tree

Module has NO transitive vscode dependency

Import directly via the @cmt/* path alias.

// encoding.test.ts — encodingUtils has no vscode imports
import { isValidUtf8 } from '@cmt/encodingUtils';

Module transitively imports vscode

Mirror the pure function logic inline in the test file. Do not import the source module — it will fail because vscode cannot be resolved at test time (even with the mock, deep transitive chains can break).

// expand.test.ts — expand.ts transitively depends on vscode
// Mirror of expand.substituteAll
function substituteAll(input: string, subs: Map<string, string>) {
    let finalString = input;
    let didReplacement = false;
    subs.forEach((value, key) => {
        if (value !== key) {
            const pattern = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            const re = new RegExp(pattern, 'g');
            finalString = finalString.replace(re, value);
            didReplacement = true;
        }
    });
    return { result: finalString, didReplacement };
}

Add a comment like // --- Mirror of <module>.<function> --- so reviewers can trace back to the source.

What setup-vscode-mock.ts provides

The mock is auto-loaded via Mocha's -r flag. It intercepts require('vscode') and returns stubs for:

  • workspace.getConfiguration() — returns a Proxy that yields undefined
  • workspace.onDidChangeConfiguration / onDidCreateFiles / onDidDeleteFiles — no-ops
  • window.createOutputChannel / showErrorMessage / showWarningMessage — no-ops
  • commands.registerCommand / executeCommand — no-ops
  • Position, Range, Uri — minimal implementations
  • EventEmitter, Disposable, TreeItem, ThemeIcon — stubs

This lets some modules with shallow vscode dependencies work. If your module only touches vscode.workspace.getConfiguration(), direct import may still work. Test it — if it fails, fall back to the mirror pattern.


Test framework

Aspect Value
Runner Mocha
Style TDD — use suite() / test(), not describe() / it()
Assertions Chai expect — import { expect } from 'chai'
Path aliases @cmt/* → src/*, @test/* → test/*

Skeleton — direct import pattern

import { expect } from 'chai';
import { myFunction } from '@cmt/myModule';

suite('[myFunction]', () => {
    test('does the expected thing', () => {
        const result = myFunction('input');
        expect(result).to.equal('expected');
    });

    test('handles edge case', () => {
        expect(myFunction('')).to.equal('');
    });
});

Skeleton — mirror pattern

import { expect } from 'chai';

/**
 * Tests for pure utility functions in src/someModule.ts.
 * Functions are mirrored here because someModule.ts transitively
 * depends on 'vscode'.
 */

// --- Mirror of someModule.helperFn ---
function helperFn(input: string): string {
    // Copy the implementation verbatim from the source
    return input.trim().toLowerCase();
}

suite('[helperFn]', () => {
    test('trims and lowercases', () => {
        expect(helperFn('  Hello  ')).to.equal('hello');
    });

    test('empty string', () => {
        expect(helperFn('')).to.equal('');
    });
});

Run command

yarn backendTests

Full command (for reference):

node ./node_modules/mocha/bin/_mocha \
  -u tdd \
  --timeout 999999 \
  --colors \
  -r ts-node/register \
  -r tsconfig-paths/register \
  -r test/unit-tests/backend/setup-vscode-mock.ts \
  ./test/unit-tests/backend/**/*.test.ts

Common pitfalls

Pitfall Fix
Cannot find module 'vscode' Module has a transitive vscode dependency — use the mirror pattern
suite is not defined Mocha TDD interface not loaded — ensure you run via yarn backendTests, not mocha directly
Import path uses relative ../../../src/ Use @cmt/* alias instead — tsconfig-paths/register resolves it
describe/it used instead of suite/test This project uses Mocha TDD style — switch to suite/test
Mock returns undefined for a config value setup-vscode-mock.ts's getConfiguration() returns undefined for everything — if your code needs a real value, you may need to extend the mock or restructure

See also: .github/copilot-instructions.md for project-wide conventions.

04 同仓库更多 Skills

microsoft
microsoft/vscode-cmake-tools

PR 验证项目搭建

validation-project

为测试某个特定的 vscode-cmake-tools pull request 创建验证项目。当被要求创建验证项目、测试 PR、验证 pull request 或搭建 PR 验证环境时使用此技能。该技能会创建一个结构化的项目目录,其中包含用于系统验证 PR 变更的文档、元数据和检查清单。

测试工程师测试与质量保障
★ 1.7k
microsoft
microsoft/vscode-cmake-tools

CMake Presets 与 Kits 双模式兼容

presets-vs-kits

在编写或审查必须同时兼容 CMake Presets 和 Kits/Variants 模式的代码时使用。涵盖配置、构建、测试、环境和生成器路径。触发词:“presets vs kits”、“useCMakePresets”、“works in both modes”。

软件开发工程师C++ 开发
★ 1.7k
microsoft
microsoft/vscode-cmake-tools

PR 贡献合规检查

pr-readiness

验证提交到 microsoft/vscode-cmake-tools 的拉取请求(PR)是否符合贡献要求。在准备、审查或定稿 PR 时使用,用于检查标题是否具有描述性、描述是否有意义、CHANGELOG 条目格式是否规范、代码正确性、回归风险、是否遵循现有模式以及是否需要更新文档。

软件开发工程师代码仓库协作管理
★ 1.7k
microsoft
microsoft/vscode-cmake-tools

cmake 配置项添加

add-setting

在添加新的 cmake.* 配置设置时使用。涉及 package.json(contributes.configuration)、package.nls.json、src/config.ts(接口 + getter)、docs/cmake-settings.md 和 CHANGELOG.md。触发词:"add setting"、"new setting"、"add configuration"。

软件开发工程师代码实现
★ 1.7k
microsoft
microsoft/vscode-cmake-tools

诊断解析器添加

add-diagnostic-parser

在为“问题(Problems)面板”添加编译器或工具输出解析器时使用。涉及 src/diagnostics/<name>.ts、src/diagnostics/build.ts、package.json(cmake.enabledOutputParsers)和 package.nls.json。触发词:"add parser"、"new diagnostic parser"、"parse compiler output"。

软件开发工程师代码实现
★ 1.7k
microsoft
microsoft/vscode-cmake-tools

新增 CMake Tools 命令

add-command

用于向 CMake Tools 添加新的 cmake.* 命令。涉及 package.json(contributes.commands)、package.nls.json、src/extension.ts(funs 数组)和 CHANGELOG.md。触发词:"add command"、"register command"、"new command palette entry"。

软件开发工程师代码实现
★ 1.7k