如何测试VSCode编程语言扩展的代码建议小部件功能?
测试编程语言扩展的自动补全功能
我已经阅读《官方指南:扩展测试》并成功运行Demo,但Demo里的示例和我要测的扩展不相关:
test('Example test', () => { assert.strictEqual([1, 2, 3].indexOf(5), -1); assert.strictEqual([1, 2, 3].indexOf(0), -1); });
我要测试一款编程语言扩展,需要在编辑器中输入代码并验证扩展是否正常工作,比如要测试Rust扩展的自动补全:打开文件a.rs,输入以下代码:
enum IpAddrKind { V4, V6, } let four = IpAddrKind::
此时编辑器应该弹出包含V4和V6的自动补全列表,我需要验证这个建议小部件里是否有这两个选项。
具体操作步骤
初始化测试文件与环境
在测试用例中,先创建并打开目标文件,确保编辑器加载对应的语言扩展:const path = require('path'); const { workspace, window } = require('vscode'); test('测试Rust自动补全', async () => { // 创建临时文件并打开 const workspaceFolder = workspace.getWorkspaceFolder(undefined); const fileUri = workspaceFolder.uri.with({ path: path.join(workspaceFolder.uri.fsPath, 'a.rs') }); const document = await workspace.openTextDocument(fileUri); await window.showTextDocument(document); });输入测试代码并触发自动补全
向编辑器写入测试代码,移动光标到触发补全的位置,手动触发补全请求:const { Position, Range, commands } = require('vscode'); // 写入测试代码 await editor.edit(editBuilder => { editBuilder.replace(new Range(new Position(0, 0), new Position(document.lineCount - 1, 0)), `enum IpAddrKind { V4, V6,
}
let four = IpAddrKind::`);
});
// 移动光标到补全触发位置
await editor.setSelection(new Position(8, 18));
// 触发自动补全
await commands.executeCommand('editor.action.triggerSuggest');
- **验证补全结果** 获取当前的补全列表,断言其中包含目标选项: ```javascript const { languages } = require('vscode'); const assert = require('assert'); // 获取补全列表 const completions = await languages.getCompletionItems(document, editor.selection.active); // 提取补全项标签 const completionLabels = completions.map(item => item.label); // 断言验证 assert.ok(completionLabels.includes('V4'), '补全列表应包含V4'); assert.ok(completionLabels.includes('V6'), '补全列表应包含V6');
完整测试用例示例
const path = require('path'); const { workspace, window, commands, languages, Position, Range } = require('vscode'); const assert = require('assert'); test('Rust枚举自动补全测试', async () => { // 1. 打开测试文件 const workspaceFolder = workspace.getWorkspaceFolder(undefined); const fileUri = workspaceFolder.uri.with({ path: path.join(workspaceFolder.uri.fsPath, 'a.rs') }); const document = await workspace.openTextDocument(fileUri); const editor = await window.showTextDocument(document); // 2. 写入测试代码 const testCode = `enum IpAddrKind { V4, V6, } let four = IpAddrKind::`; await editor.edit(editBuilder => { editBuilder.replace(new Range(new Position(0, 0), new Position(document.lineCount - 1, 0)), testCode); }); // 3. 定位光标并触发补全 await editor.setSelection(new Position(8, 18)); await commands.executeCommand('editor.action.triggerSuggest'); // 4. 获取并验证补全结果 const completions = await languages.getCompletionItems(document, editor.selection.active); const completionLabels = completions.map(item => item.label); assert.ok(completionLabels.includes('V4'), '补全列表应包含V4'); assert.ok(completionLabels.includes('V6'), '补全列表应包含V6'); });
内容的提问来源于stack exchange,提问作者alwaysday1
相关产品推荐
相关产品推荐

