Vitest API
Vitest 實例需要目前的測試模式。模式可以是:
- 執行測試時為
test
- 執行基準測試時為
benchmark
實驗性
Vitest 3 新功能
Vitest 3 在穩定公開 API 方面又邁進了一步。為此,我們棄用並移除了 Vitest
類別上一些先前公開的方法,並將這些 API 設為私有:
configOverride
(請改用setGlobalTestNamePattern
或enableSnapshotUpdate
)coverageProvider
filenamePattern
runningPromise
closingPromise
isCancelling
coreWorkspaceProject
resolvedProjects
_browserLastPort
_options
reporters
vitenode
runner
pool
setServer
_initBrowserServers
rerunTask
changeProjectName
changeNamePattern
changeFilenamePattern
rerunFailed
_createRootProject
(重新命名為_ensureRootProject
,但仍為私有)filterTestsBySource
(這已移至新的內部vitest.specifications
實例)runFiles
(請改用runTestSpecifications
)onAfterSetServer
這些 API 已棄用:
invalidates
changedTests
(請改用onFilterWatchedSpecification
)server
(請改用vite
)getProjectsByTestFile
(請改用getModuleSpecifications
)getFileWorkspaceSpecs
(請改用getModuleSpecifications
)getModuleProjects
(請自行透過this.projects
篩選)updateLastChanged
(重新命名為invalidateFile
)globTestSpecs
(請改用globTestSpecifications
)globTestFiles
(請改用globTestSpecifications
)listFile
(請改用getRelevantTestSpecifications
)
mode
test
測試模式只會呼叫 test
或 it
內的函式,並在遇到 bench
時拋出錯誤。此模式使用設定中的 include
和 exclude
選項來尋找測試檔案。
benchmark 實驗性
基準測試模式會呼叫 bench
函式,並在遇到 test
或 it
時拋出錯誤。此模式使用設定中的 benchmark.include
和 benchmark.exclude
選項來尋找基準測試檔案。
config
根 (或全域) 設定。如果定義了專案,它們會將此設定作為 globalConfig
參考。
WARNING
這是 Vitest 設定,它不會擴展 Vite 設定。它只包含 test
屬性中解析過的值。
vite
這是一個全域 ViteDevServer
實例。
state 實驗性
WARNING
公開 state
是一個實驗性 API (除了 vitest.state.getReportedEntity
)。破壞性變更可能不遵循 SemVer,使用時請鎖定 Vitest 的版本。
全域狀態儲存目前測試的相關資訊。它預設使用 @vitest/runner
中的相同 API,但我們建議改為呼叫 @vitest/runner
API 上的 state.getReportedEntity()
來使用 報告任務 API:
const task = vitest.state.idMap.get(taskId); // 舊 API
const testCase = vitest.state.getReportedEntity(task); // 新 API
未來,舊 API 將不再對外公開。
snapshot
全域快照管理器。Vitest 使用 snapshot.add
方法來追蹤所有快照。
您可以透過 vitest.snapshot.summary
屬性取得快照的最新摘要。
cache
快取管理器,用於儲存最新測試結果和測試檔案的統計資訊。在 Vitest 本身中,這僅由預設排序器用於排序測試。
projects
一個包含使用者專案的 測試專案 陣列。如果使用者未明確指定專案,此陣列將只包含一個 根專案。
Vitest 將確保此陣列中始終至少有一個專案。如果使用者指定了不存在的 --project
名稱,Vitest 會在此陣列定義前拋出錯誤。
getRootProject
function getRootProject(): TestProject;
此方法會傳回根測試專案。根專案通常不執行任何測試,且不會包含在 vitest.projects
中,除非使用者在其設定中明確包含根設定,或根本沒有定義任何專案。
根專案的主要目標是建立全域設定。事實上,rootProject.config
直接參考 rootProject.globalConfig
和 vitest.config
:
(rootProject.config === rootProject.globalConfig) === rootProject.vitest.config;
provide
function provide<T extends keyof ProvidedContext & string>(
key: T,
value: ProvidedContext[T]
): void;
Vitest 提供了 provide
方法,它是 vitest.getRootProject().provide
的簡寫。您可以使用此方法將值從主執行緒傳遞到測試。所有值在儲存之前都會使用 structuredClone
檢查,但值本身不會被複製。
若要在測試中接收值,您需要從 vitest
入口點匯入 inject
方法:
import { inject } from 'vitest';
const port = inject('wsPort'); // 3000
為了更好的型別安全,我們鼓勵您擴充 ProvidedContext
的型別:
import { createVitest } from 'vitest/node';
const vitest = await createVitest('test', {
watch: false,
});
vitest.provide('wsPort', 3000);
declare module 'vitest' {
export interface ProvidedContext {
wsPort: number;
}
}
WARNING
從技術上來說,provide
是 TestProject
的方法,因此它僅限於特定專案。然而,所有專案都繼承了根專案的值,這使得 vitest.provide
成為將值傳遞給測試的通用方法。
getProvidedContext
function getProvidedContext(): ProvidedContext;
這會傳回根上下文物件。這是 vitest.getRootProject().getProvidedContext
的簡寫。
getProjectByName
function getProjectByName(name: string): TestProject;
此方法會依據名稱傳回專案。類似於呼叫 vitest.projects.find
。
WARNING
如果專案不存在,此方法將傳回根專案。請務必再次檢查名稱,以確保傳回的專案是您所尋找的。
如果使用者未自訂名稱,Vitest 會將空字串指定為名稱。
globTestSpecifications
function globTestSpecifications(
filters?: string[]
): Promise<TestSpecification[]>;
此方法會透過使用 project.globTestFiles
收集所有專案中的每個測試,以建構新的 測試規格。它接受字串篩選器來比對測試檔案,這些篩選器與 CLI 支援的篩選器 相同。
此方法會自動快取所有測試規格。當您下次呼叫 getModuleSpecifications
時,它將傳回相同的規格,除非在此之前已呼叫 clearSpecificationsCache
。
WARNING
截至 Vitest 3,如果 poolMatchGlob
包含多個池或啟用 typecheck
,則可能有多個具有相同模組 ID (檔案路徑) 的測試規格。這種可能性將在 Vitest 4 中移除。
const specifications = await vitest.globTestSpecifications(['my-filter']);
// [TestSpecification{ moduleId: '/tests/my-filter.test.ts' }]
console.log(specifications);
getRelevantTestSpecifications
function getRelevantTestSpecifications(
filters?: string[]
): Promise<TestSpecification[]>;
此方法會透過呼叫 project.globTestFiles
來解析每個測試規格。它接受字串篩選器來比對測試檔案,這些篩選器與 CLI 支援的篩選器 相同。如果指定了 --changed
旗標,則清單將被篩選,僅包含已變更的檔案。getRelevantTestSpecifications
不會執行任何測試檔案。
WARNING
此方法可能很慢,因為它需要根據 --changed
旗標進行篩選。如果您只需要測試檔案清單,請勿使用它。
- 如果您需要取得已知測試檔案的規格清單,請改用
getModuleSpecifications
。 - 如果您需要取得所有可能測試檔案的清單,請使用
globTestSpecifications
。
mergeReports
function mergeReports(directory?: string): Promise<TestRunResult>;
合併位於指定目錄中的多個執行報告 (若未指定,則使用 --merge-reports
的值)。此值也可以在 config.mergeReports
上設定 (預設情況下,它會讀取 .vitest-reports
資料夾)。
請注意,directory
將始終相對於工作目錄進行解析。
如果設定了 config.mergeReports
,此方法會由 startVitest
自動呼叫。
collect
function collect(filters?: string[]): Promise<TestRunResult>;
執行測試檔案而不執行測試回呼。collect
會傳回未處理的錯誤和一個 測試模組 陣列。它接受字串篩選器來比對測試檔案,這些篩選器與 CLI 支援的篩選器 相同。
此方法會根據設定中的 include
、exclude
和 includeSource
值來解析測試規格。請參閱 project.globTestFiles
以了解更多資訊。如果指定了 --changed
旗標,則清單將被篩選,僅包含已變更的檔案。
WARNING
請注意,Vitest 不使用靜態分析來收集測試。Vitest 會單獨執行每個測試檔案,就像它執行常規測試一樣。
這會使得此方法非常慢,除非您在收集測試之前禁用隔離。
start
function start(filters?: string[]): Promise<TestRunResult>;
初始化報告器、覆蓋率提供者並執行測試。此方法接受字串篩選器來比對測試檔案,這些篩選器與 CLI 支援的篩選器 相同。
WARNING
如果同時呼叫了 vitest.init()
,則不應呼叫此方法。如果您需要在 Vitest 初始化後執行測試,請改用 runTestSpecifications
或 rerunTestSpecifications
。
如果未設定 config.mergeReports
和 config.standalone
,此方法會由 startVitest
自動呼叫。
init
function init(): Promise<void>;
初始化報告器和覆蓋率提供者。此方法不執行任何測試。如果指定了 --watch
旗標,即使未呼叫此方法,Vitest 仍會執行已變更的測試。
在內部,此方法僅在 --standalone
旗標啟用時呼叫。
WARNING
如果同時呼叫了 vitest.start()
,則不應呼叫此方法。
如果設定了 config.standalone
,此方法會由 startVitest
自動呼叫。
getModuleSpecifications
function getModuleSpecifications(moduleId: string): TestSpecification[];
傳回與模組 ID 相關的測試規格清單。該 ID 應已解析為絕對檔案路徑。如果 ID 不符合 include
或 includeSource
模式,則傳回的陣列將為空。
此方法可以根據 moduleId
和 pool
傳回已快取的規格。但請注意,project.createSpecification
始終會傳回新實例,並且不會自動快取。然而,當呼叫 runTestSpecifications
時,規格會自動快取。
WARNING
截至 Vitest 3,此方法使用快取來檢查檔案是否為測試。為確保快取不為空,請至少呼叫 globTestSpecifications
一次。
clearSpecificationsCache
function clearSpecificationsCache(moduleId?: string): void;
當呼叫 globTestSpecifications
或 runTestSpecifications
時,Vitest 會自動快取每個檔案的測試規格。此方法會根據第一個參數,清除指定檔案的快取或整個快取。
runTestSpecifications
function runTestSpecifications(
specifications: TestSpecification[],
allTestsRun = false
): Promise<TestRunResult>;
此方法根據收到的 規格 執行每個測試。第二個參數 allTestsRun
由覆蓋率提供者使用,以確定是否需要在根目錄中的 每個 檔案上進行覆蓋率檢測 (這僅在啟用覆蓋率且 coverage.all
設定為 true
時才重要)。
WARNING
此方法不會觸發 onWatcherRerun
、onWatcherStart
和 onTestsRerun
回呼。如果您是根據檔案變更來重新執行測試,請考慮改用 rerunTestSpecifications
。
rerunTestSpecifications
function rerunTestSpecifications(
specifications: TestSpecification[],
allTestsRun = false
): Promise<TestRunResult>;
此方法觸發 reporter.onWatcherRerun
和 onTestsRerun
事件,然後使用 runTestSpecifications
執行測試。如果主程序中沒有錯誤,它將觸發 reporter.onWatcherStart
事件。
updateSnapshot
function updateSnapshot(files?: string[]): Promise<TestRunResult>;
更新指定檔案中的快照。如果未提供檔案,它將更新包含失敗測試和過時快照的檔案。
collectTests
function collectTests(
specifications: TestSpecification[]
): Promise<TestRunResult>;
執行測試檔案而不執行測試回呼。collectTests
會傳回未處理的錯誤和一個 測試模組 陣列。
此方法與 collect
完全相同,但您需要自行提供測試規格。
WARNING
請注意,Vitest 不使用靜態分析來收集測試。Vitest 會單獨執行每個測試檔案,就像它執行常規測試一樣。
這會使得此方法非常慢,除非您在收集測試之前禁用隔離。
cancelCurrentRun
function cancelCurrentRun(reason: CancelReason): Promise<void>;
此方法將會優雅地取消所有正在進行的測試。它會等待已啟動的測試完成執行,並且不會執行已排程但尚未啟動的測試。
setGlobalTestNamePattern
function setGlobalTestNamePattern(pattern: string | RegExp): void;
此方法會覆寫全域 測試名稱模式。
WARNING
此方法不會開始執行任何測試。若要使用更新的模式執行測試,請呼叫 runTestSpecifications
。
resetGlobalTestNamePattern
function resetGlobalTestNamePattern(): void;
此方法會重設 測試名稱模式。這表示 Vitest 現在不會跳過任何測試。
WARNING
此方法不會開始執行任何測試。若要不使用模式執行測試,請呼叫 runTestSpecifications
。
enableSnapshotUpdate
function enableSnapshotUpdate(): void;
啟用允許在執行測試時更新快照的模式。在此方法呼叫後執行的每個測試都將更新快照。若要停用此模式,請呼叫 resetSnapshotUpdate
。
WARNING
此方法不會開始執行任何測試。若要更新快照,請使用 runTestSpecifications
執行測試。
resetSnapshotUpdate
function resetSnapshotUpdate(): void;
禁用允許在執行測試時更新快照的模式。此方法不會開始執行任何測試。
invalidateFile
function invalidateFile(filepath: string): void;
此方法會使每個專案快取中的檔案失效。如果您依賴自己的監看器,這會特別有用,因為 Vite 的快取會保留在記憶體中。
DANGER
如果您停用 Vitest 的監看器但保持 Vitest 執行,則手動使用此方法清除快取非常重要,因為無法停用快取。此方法還將使檔案的匯入器失效。
import
function import<T>(moduleId: string): Promise<T>
使用 Vite 模組執行器匯入檔案。該檔案將由 Vite 使用全域設定進行轉換,並在單獨的上下文中執行。請注意,moduleId
將相對於 config.root
。
DANGER
project.import
會重複使用 Vite 的模組圖,因此使用常規匯入來匯入相同的模組將會傳回不同的模組:
import * as staticExample from './example.js';
const dynamicExample = await vitest.import('./example.js');
dynamicExample !== staticExample; // ✅
INFO
在內部,Vitest 使用此方法匯入全域設定、自訂覆蓋率提供者和自訂報告器。這表示只要它們屬於同一個 Vite 伺服器,它們就會共享相同的模組圖。
close
function close(): Promise<void>;
關閉所有專案及其相關資源。此方法只能呼叫一次;關閉承諾會被快取,直到伺服器重新啟動。
exit
function exit(force = false): Promise<void>;
關閉所有專案並結束程序。如果 force
設定為 true
,則程序將在關閉專案後立即結束。
如果程序在 config.teardownTimeout
毫秒後仍處於活動狀態,此方法還將強制呼叫 process.exit()
。
shouldKeepServer
function shouldKeepServer(): boolean;
如果測試完成後伺服器應保持執行,此方法將傳回 true
。這通常表示 watch
模式已啟用。
onServerRestart
function onServerRestart(fn: OnServerRestartHandler): void;
註冊一個處理常式,當伺服器因設定變更而重新啟動時,此處理常式將被呼叫。
onCancel
function onCancel(fn: (reason: CancelReason) => Awaitable<void>): void;
註冊一個處理常式,當測試執行被 vitest.cancelCurrentRun
取消時,此處理常式將被呼叫。
onClose
function onClose(fn: () => Awaitable<void>): void;
註冊一個處理常式,當伺服器關閉時,此處理常式將被呼叫。
onTestsRerun
function onTestsRerun(fn: OnTestsRerunHandler): void;
註冊一個處理常式,當測試重新執行時,此處理常式將被呼叫。當手動呼叫 rerunTestSpecifications
,或檔案變更且內建監看器排程重新執行時,測試可以重新執行。
onFilterWatchedSpecification
function onFilterWatchedSpecification(
fn: (specification: TestSpecification) => boolean
): void;
註冊一個處理常式,當檔案變更時,此處理常式將被呼叫。此回呼應傳回 true
或 false
,以指示測試檔案是否需要重新執行。
透過此方法,您可以掛接到預設的監看器邏輯中,以延遲或捨棄使用者目前不想追蹤的測試:
const continuesTests: string[] = [];
myCustomWrapper.onContinuesRunEnabled(testItem =>
continuesTests.push(item.fsPath)
);
vitest.onFilterWatchedSpecification(specification =>
continuesTests.includes(specification.moduleId)
);
Vitest 可以根據 pool
或 locations
選項為同一個檔案建立不同的規格,因此請勿依賴參考。Vitest 還可以從 vitest.getModuleSpecifications
傳回快取的規格,此快取基於 moduleId
和 pool
。請注意,project.createSpecification
始終會傳回新實例。
matchesProjectFilter 3.1.0+
function matchesProjectFilter(name: string): boolean;
檢查名稱是否符合目前的 專案篩選器。如果沒有專案篩選器,這將始終傳回 true
。
無法透過程式碼變更 --project
CLI 選項。