[英]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.