[英]Testing a VSCode extension that involves opening a folder/workspace
我正在开发一个 VSCode 扩展,它考虑了当前在工作区中打开的文件的路径。
因此,为了进行可重现的测试,我尝试在 VSCode 中打开测试文件夹本身,然后打开其中的测试文件,如下所示:
import * as vscode from "vscode";
test("whatever", async function() {
let workspaceUri = vscode.Uri.file(__dirname);
// the tests stop here...
await vscode.commands.executeCommand("vscode.openFolder", workspaceUri);
await vscode.workspace.openTextDocument(__filename);
})
问题是当我这样做时,正如此处可能提到的那样,测试只是在我实际测试我的代码之前停止运行。
有没有一种方法可以安全地打开工作区并在测试期间使用它?
查看测试扩展的文档: Testing-extensions-docs
在开发中的扩展程序的.vscode/launch.json文件中,您可以像这样传递参数(来自文档):
"args": ["file or folder name", "--extensionDevelopmentPath=${workspaceRoot}", "--extensionTestsPath=${workspaceRoot}/out/test" ]
因此,您可以创建一个包含您在配置中指定的文件夹中关心的所有文件的测试目录结构,并将这些目录/文件添加到您的.vscodeignore (默认测试目录已经在那里)。
到目前为止,我一直在使用的替代方法是使用具有以下内容的bash 脚本:
#!/bin/bash
# $0 = command itself
# $1 = extension-directory(relative path)
# $2 = process-id of code to kill
[ -z "$1" ] && { echo "path-argument not supplied"; exit 1; }
[ -z "$2" ] || { xkill -id $2; }
cd $1
vsce package
file=$(find . -name "*.vsix")
code --install-extension $file
code &
echo $!
剩下的就是在启动的代码实例中打开一个文件夹并执行任何有问题的命令。 从长远来看,建立一个合适的测试环境对我来说似乎更有利可图,至少在可以预测必须进行许多测试的时候是这样。
您还可以使用VSBrowser.instance.openResources(path)在 VSCode 实例中打开工作区/文件夹;
import { WebDriver, VSBrowser } from 'vscode-extension-tester';
import path = require('path');
...
suite('Sample Test suite XYZ', () => {
const test_project_path = path.join(__dirname, "path", "to", "prj");
setup(async () => {
driver = VSBrowser.instance.driver;
driver.manage().timeouts().implicitlyWait(1000);
});
test("Open a workspace in VSCode instance", async () => {
await VSBrowser.instance.openResources(path.resolve(test_project_path));
});
});
...
接受的答案在 2023 年对我不起作用。我无法通过修改launch.json
让 VS Code 打开工作区。
相反, @vscode/test-electron runTests采用launchArgs
参数。 如果第一个参数是一个目录,它将作为工作区打开。
await runTests({extensionDevelopmentPath,
extensionTestsPath,
launchArgs:[path_to_directory]
});
为了进行测试,我将其设置为由tmp-promise创建的临时目录。 我的runTests.ts
是:
import * as path from "path";
import { runTests } from "@vscode/test-electron";
import { file, dir } from 'tmp-promise';
async function main() {
try {
const extensionDevelopmentPath = path.resolve(__dirname, "../../");
const extensionTestsPath = path.resolve(__dirname, "./suite/index");
const {path:tempdir, cleanup} = await dir({unsafeCleanup:true});
await runTests({extensionDevelopmentPath,
extensionTestsPath,
launchArgs:[tempdir] });
cleanup();
} catch (err) {
console.error("Failed to run tests");
process.exit(1);
}
}
main();
VS Code 测试存储库中的示例是寻找好的、可能是最新的示例的好地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.