執行測試
WARNING
本指南旨在說明如何透過 Node.js 腳本使用進階 API 執行測試。如果您僅需執行測試,則可能無需此功能。此功能主要供函式庫開發者使用。
由於此為實驗性 API,重大變更可能不遵循 SemVer 規範,建議使用時鎖定 Vitest 的版本。
Vitest 提供了兩種啟動方式:
startVitest
會啟動 Vitest、驗證所需套件是否已安裝,並立即執行測試。createVitest
僅啟動 Vitest,但不執行任何測試。
startVitest
import { startVitest } from 'vitest/node';
const vitest = await startVitest(
'test',
[], // CLI 篩選器
{}, // 覆寫測試設定
{}, // 覆寫 Vite 設定
{} // 自訂 Vitest 選項
);
const testModules = vitest.state.getTestModules();
for (const testModule of testModules) {
console.log(testModule.moduleId, testModule.ok() ? 'passed' : 'failed');
}
TIP
TestModule
、TestSuite
與 TestCase
API 並非實驗性功能,自 Vitest 2.1 起遵循 SemVer 規範。
createVitest
建立一個 Vitest 實例,但不執行測試。
createVitest
方法不會驗證所需套件是否已安裝,也不會遵循 config.standalone
或 config.mergeReports
設定。即使 watch
功能被禁用,Vitest 也不會自動關閉。
import { createVitest } from 'vitest/node';
const vitest = await createVitest(
'test',
{}, // 覆寫測試設定
{}, // 覆寫 Vite 設定
{} // 自訂 Vitest 選項
);
// 當 `vitest.cancelCurrentRun()` 被呼叫時執行此函式
vitest.onCancel(() => {});
// 在 `vitest.close()` 呼叫期間執行此函式
vitest.onClose(() => {});
// 當 Vitest 重新執行測試檔案時執行此函式
vitest.onTestsRerun(files => {});
try {
// 如果測試失敗,這會將 `process.exitCode` 設定為 1,
// 且不會自動關閉程序。
await vitest.start(['my-filter']);
} catch (err) {
// 此處可能會拋出錯誤:
// 若找不到檔案,則會拋出 "FilesNotFoundError"。
// 若使用 `--changed` 且倉庫未初始化,則會拋出 "GitNotFoundError"。
} finally {
await vitest.close();
}
如果您打算保留 Vitest
實例,請務必至少呼叫 init
。這將初始化報告器與覆蓋率提供者,但不會執行任何測試。即使您不打算使用 Vitest 監視器,但希望保持實例運行,也建議啟用 watch
模式。Vitest 依賴此標誌來確保其部分功能在持續執行過程中正常運作。
報告器初始化後,如果需要手動執行測試,請使用 runTestSpecifications
或 rerunTestSpecifications
:
watcher.on('change', async file => {
const specifications = vitest.getModuleSpecifications(file);
if (specifications.length) {
vitest.invalidateFile(file);
// 如果您不希望呼叫 "reporter.onWatcher*" 鉤子,可以使用 runTestSpecifications。
await vitest.rerunTestSpecifications(specifications);
}
});
WARNING
上述範例顯示了禁用預設監視器行為的潛在用例。預設情況下,當檔案變更時,Vitest 會自動重新執行測試。
另請注意,除非檔案已經由 globTestSpecifications
處理過,否則 getModuleSpecifications
將無法解析測試檔案。如果檔案是剛建立的,請改用 project.matchesGlobPattern
:
watcher.on('add', async file => {
const specifications = [];
for (const project of vitest.projects) {
if (project.matchesGlobPattern(file)) {
specifications.push(project.createSpecification(file));
}
}
if (specifications.length) {
await vitest.rerunTestSpecifications(specifications);
}
});
在需要禁用監視器的情況下,您可以從 Vite 5.3 開始,在 Vite 設定中傳遞 server.watch: null
或 server.watch: { ignored: ['*/*'] }
:
await createVitest(
'test',
{},
{
plugins: [
{
name: 'stop-watcher',
async configureServer(server) {
await server.watcher.close();
},
},
],
server: {
watch: null,
},
}
);