測試擴充套件
Visual Studio Code 支援執行和除錯您的擴充套件的測試。這些測試將在一個名為擴充套件開發主機的特殊 VS Code 例項中執行,並具有對 VS Code API 的完全訪問許可權。我們將這些測試稱為整合測試,因為它們超越了可以在沒有 VS Code 例項的情況下執行的單元測試。本文件重點介紹 VS Code 整合測試。
概述
如果您正在使用 Yeoman Generator 來搭建擴充套件,那麼整合測試已經為您建立好了。
在生成的擴充套件中,您可以使用 npm run test
或 yarn test
來執行整合測試,它會
- 下載並解壓最新版本的 VS Code。
- 執行擴充套件測試執行器指令碼指定的 Mocha 測試。
快速設定:測試 CLI
VS Code 團隊釋出了一個命令列工具來執行擴充套件測試。您可以在 擴充套件示例倉庫 中找到一個示例。
測試 CLI 提供了快速設定,並且還允許您使用 Extension Test Runner 輕鬆執行和除錯 VS Code UI 的測試。CLI 在底層專門使用 Mocha。
首先,您需要安裝 @vscode/test-cli
模組以及 @vscode/test-electron
模組,後者允許在 VS Code Desktop 中執行測試。
npm install --save-dev @vscode/test-cli @vscode/test-electron
安裝模組後,您將擁有 vscode-test
命令列,您可以將其新增到 package.json
的 scripts
部分。
{
"name": "my-cool-extension",
"scripts": {
+ "test": "vscode-test"
vscode-test
會在當前工作目錄的相對路徑中查詢 .vscode-test.js/mjs/cjs
檔案。此檔案提供了測試執行器的配置,您可以在此處找到完整的定義。
常見選項包括
- (必需)
files
- 包含要執行的測試的模式、模式列表或絕對路徑。 version
- 用於執行測試的 VS Code 版本(預設為stable
)。workspaceFolder
- 在測試期間開啟的工作區路徑。extensionDevelopmentPath
- 您的擴充套件資料夾路徑(預設為配置檔案所在目錄)。mocha
- 一個包含要傳遞給 Mocha 的附加 選項 的物件。
配置可以很簡單
// .vscode-test.js
const { defineConfig } = require('@vscode/test-cli');
module.exports = defineConfig({ files: 'out/test/**/*.test.js' });
...也可以更高階
// .vscode-test.js
const { defineConfig } = require('@vscode/test-cli');
module.exports = defineConfig([
{
label: 'unitTests',
files: 'out/test/**/*.test.js',
version: 'insiders',
workspaceFolder: './sampleWorkspace',
mocha: {
ui: 'tdd',
timeout: 20000
}
}
// you can specify additional test configurations, too
]);
如果您透過傳遞陣列定義了多個配置,當您執行 vscode-test
時,它們將按順序執行。您可以透過 label
進行過濾,並使用 --label
標誌單獨執行它們,例如 vscode-test --label unitTests
。執行 vscode-test --help
可檢視完整的命令列選項集。
測試指令碼
CLI 設定好後,您就可以編寫和執行測試了。測試指令碼可以訪問 VS Code API,並在 Mocha 下執行。這是一個示例 (src/test/suite/extension.test.ts)
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
// import * as myExtension from '../extension';
suite('Extension Test Suite', () => {
suiteTeardown(() => {
vscode.window.showInformationMessage('All tests done!');
});
test('Sample test', () => {
assert.strictEqual(-1, [1, 2, 3].indexOf(5));
assert.strictEqual(-1, [1, 2, 3].indexOf(0));
});
});
您可以執行此測試,使用 npm test
命令,或者在安裝 Extension Test Runner 後使用 VS Code 中的 Test: Run All Tests 命令。您還可以使用 Test: Debug All Tests 命令除錯測試。
高階設定:您自己的執行器
您可以在 helloworld-test-sample 中找到本指南的配置。本文件的其餘部分將在示例的背景下解釋這些檔案。
- 測試指令碼 (
src/test/runTest.ts
) - 測試執行器指令碼 (
src/test/suite/index.ts
)
VS Code 提供了兩個用於執行擴充套件測試的 CLI 引數:--extensionDevelopmentPath
和 --extensionTestsPath
。
例如
# - Launches VS Code Extension Host
# - Loads the extension at <EXTENSION-ROOT-PATH>
# - Executes the test runner script at <TEST-RUNNER-SCRIPT-PATH>
code \
--extensionDevelopmentPath=<EXTENSION-ROOT-PATH> \
--extensionTestsPath=<TEST-RUNNER-SCRIPT-PATH>
測試指令碼 (src/test/runTest.ts
) 使用 @vscode/test-electron
API 簡化了下載、解壓和使用擴充套件測試引數啟動 VS Code 的過程。
import * as path from 'path';
import { runTests } from '@vscode/test-electron';
async function main() {
try {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = path.resolve(__dirname, '../../');
// The path to the extension test runner script
// Passed to --extensionTestsPath
const extensionTestsPath = path.resolve(__dirname, './suite/index');
// Download VS Code, unzip it and run the integration test
await runTests({ extensionDevelopmentPath, extensionTestsPath });
} catch (err) {
console.error(err);
console.error('Failed to run tests');
process.exit(1);
}
}
main();
@vscode/test-electron
API 還允許
- 使用特定工作區啟動 VS Code。
- 下載不同版本的 VS Code,而不是最新的穩定版本。
- 使用附加的 CLI 引數啟動 VS Code。
您可以在 microsoft/vscode-test 中找到更多 API 使用示例。
測試執行器指令碼
執行擴充套件整合測試時,--extensionTestsPath
指向測試執行器指令碼 (src/test/suite/index.ts
),該指令碼以程式設計方式執行測試套件。下面是 helloworld-test-sample
的測試執行器指令碼,它使用 Mocha 執行測試套件。您可以將其作為起點,並使用 Mocha 的 API 自定義您的設定。您也可以用任何其他可以程式設計方式執行的測試框架替換 Mocha。
import * as path from 'path';
import * as Mocha from 'mocha';
import { glob } from 'glob';
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: 'tdd',
color: true
});
const testsRoot = path.resolve(__dirname, '..');
return new Promise((c, e) => {
glob('**/**.test.js', { cwd: testsRoot })
.then(files => {
// Add files to the test suite
files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
e(err);
}
})
.catch(err => {
return e(err);
});
});
}
測試執行器指令碼和 *.test.js
檔案都可以訪問 VS Code API。
這是一個示例測試 (src/test/suite/extension.test.ts)
import * as assert from 'assert';
import { after } from 'mocha';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
// import * as myExtension from '../extension';
suite('Extension Test Suite', () => {
after(() => {
vscode.window.showInformationMessage('All tests done!');
});
test('Sample test', () => {
assert.strictEqual(-1, [1, 2, 3].indexOf(5));
assert.strictEqual(-1, [1, 2, 3].indexOf(0));
});
});
除錯測試
除錯測試類似於除錯擴充套件。
這是一個 launch.json
偵錯程式配置示例
{
"version": "0.2.0",
"configurations": [
{
"name": "Extension Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
],
"outFiles": ["${workspaceFolder}/out/test/**/*.js"]
}
]
}
提示
使用 Insiders 版本進行擴充套件開發
由於 VS Code 的限制,如果您正在使用 VS Code 穩定版並嘗試在 CLI 上執行整合測試,它將丟擲錯誤。
Running extension tests from the command line is currently only supported if no other instance of Code is running.
通常,如果您從 CLI 執行擴充套件測試,那麼執行測試的版本不能已經正在執行。作為一種解決方法,您可以在 VS Code Stable 中執行測試,並使用 VS Code Insiders 進行開發。只要您不在 VS Code Insiders 中從 CLI 執行測試,而是在 VS Code Stable 中執行,這種設定就會正常工作。
另一種方法是從 VS Code 內部的除錯啟動配置中執行擴充套件測試。這有一個額外的優勢,您甚至可以除錯這些測試。
除錯時停用其他擴充套件
當您在 VS Code 中除錯擴充套件測試時,VS Code 會使用全域性安裝的 VS Code 例項並載入所有已安裝的擴充套件。您可以將 --disable-extensions
配置新增到 launch.json
或 @vscode/test-electron
的 runTests
API 的 launchArgs
選項中。
{
"version": "0.2.0",
"configurations": [
{
"name": "Extension Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--disable-extensions",
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
],
"outFiles": ["${workspaceFolder}/out/test/**/*.js"]
}
]
}
await runTests({
extensionDevelopmentPath,
extensionTestsPath,
/**
* A list of launch arguments passed to VS Code executable, in addition to `--extensionDevelopmentPath`
* and `--extensionTestsPath` which are provided by `extensionDevelopmentPath` and `extensionTestsPath`
* options.
*
* If the first argument is a path to a file/folder/workspace, the launched VS Code instance
* will open it.
*
* See `code --help` for possible arguments.
*/
launchArgs: ['--disable-extensions']
});
使用 @vscode/test-electron
進行自定義設定
有時您可能希望執行自定義設定,例如在開始測試之前執行 code --install-extension
來安裝另一個擴充套件。@vscode/test-electron
具有更精細的 API 來適應這種情況。
import * as cp from 'child_process';
import * as path from 'path';
import {
downloadAndUnzipVSCode,
resolveCliArgsFromVSCodeExecutablePath,
runTests
} from '@vscode/test-electron';
async function main() {
try {
const extensionDevelopmentPath = path.resolve(__dirname, '../../../');
const extensionTestsPath = path.resolve(__dirname, './suite/index');
const vscodeExecutablePath = await downloadAndUnzipVSCode('1.40.1');
const [cliPath, ...args] = resolveCliArgsFromVSCodeExecutablePath(vscodeExecutablePath);
// Use cp.spawn / cp.exec for custom setup
cp.spawnSync(
cliPath,
[...args, '--install-extension', '<EXTENSION-ID-OR-PATH-TO-VSIX>'],
{
encoding: 'utf-8',
stdio: 'inherit'
}
);
// Run the extension test
await runTests({
// Use the specified `code` executable
vscodeExecutablePath,
extensionDevelopmentPath,
extensionTestsPath
});
} catch (err) {
console.error('Failed to run tests');
process.exit(1);
}
}
main();
後續步驟
- 持續整合 - 在 Azure DevOps 等持續整合服務中執行您的擴充套件測試。