設定 Vitest
若要建立 Vitest 設定檔,請遵循 指南。在繼續之前,請務必了解 Vitest 設定解析的工作原理。
警告
所有在此列出的選項都位於設定檔內 test
屬性中
export default defineConfig({
test: {
exclude: [],
},
})
提示
除了下列選項外,您還可以從 Vite 使用任何設定選項。例如,define
用於定義全域變數,或 resolve.alias
用於定義別名。
所有在 工作區 專案設定中不支援的設定選項,其旁邊都會標示 * 符號。
include
- 類型:
string[]
- 預設值:
['**/*.{test,spec}.?(c|m)[jt]s?(x)']
- CLI:
vitest [...include]
,vitest **/*.test.js
與您的測試檔案相符的 glob 模式清單。
exclude
- 類型:
string[]
- 預設:
['**/node_modules/**', '**/dist/**', '**/cypress/**', '**/.{idea,git,cache,output,temp}/**', '**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*']
- CLI:
vitest --exclude "**/excluded-file"
應從測試檔案中排除的一系列 glob 模式。
警告
此選項不會影響覆蓋率。如果您需要從覆蓋率報告中移除特定檔案,請使用 coverage.exclude
。
這是唯一不會在您提供 CLI 標記時覆寫組態的選項。所有透過 --exclude
標記新增的 glob 模式都將新增至組態的 exclude
。
includeSource
- 類型:
string[]
- 預設:
[]
包含用於來源內測試檔案的 glob。
定義後,Vitest 將執行所有在其中包含 import.meta.vitest
的相符檔案。
server 0.34.0+
- 類型:
{ sourcemap?, deps?, ... }
Vite-Node 伺服器選項。
server.sourcemap
- 類型:
'inline' | boolean
- 預設:
'inline'
將內嵌原始碼對應注入至模組。
server.debug
- 類型:
{ dumpModules?, loadDumppedModules? }
Vite-Node 除錯器選項。
server.debug.dumpModules
- 類型:
boolean | string
將轉換後的模組傾印至檔案系統。傳遞字串將傾印至指定路徑。
server.debug.loadDumppedModules
- 類型:
boolean
在存在時從檔案系統讀取傾印的模組。透過修改檔案系統中的傾印結果,有助於除錯。
server.deps
- 類型:
{ external?, inline?, ... }
處理相依性解析。
server.deps.external
- 類型:
(字串 | RegExp)[]
- 預設:
[/\/node_modules\//]
外部化表示 Vite 會略過套件至原生 Node。外部化的相依性不會套用至 Vite 的轉換器和解析器,因此它們不支援重新載入時的 HMR。預設情況下,node_modules
內的所有套件都會被外部化。
這些選項支援套件名稱,因為它們寫在 node_modules
中或在 deps.moduleDirectories
內指定。例如,位於 packages/some-name
內的套件 @company/some-name
應指定為 some-name
,而 packages
應包含在 deps.moduleDirectories
中。基本上,Vitest 始終檢查檔案路徑,而不是實際的套件名稱。
如果使用正規表示法,Vitest 會在檔案路徑上呼叫它,而不是套件名稱。
server.deps.inline
- 類型:
(字串 | RegExp)[] | true
- 預設:
[]
Vite 會處理內嵌模組。這有助於處理以 ESM 格式(Node 無法處理)提供 .js
的套件。
如果為 true
,每個相依性都會被內嵌。在 ssr.noExternal
中指定的相依性預設會被內嵌。
server.deps.fallbackCJS
- 類型
布林值
- 預設:
false
當相依性是有效的 ESM 套件時,請嘗試根據路徑猜測 cjs 版本。如果相依性有錯誤的 ESM 檔案,這可能會有所幫助。
如果套件在 ESM 和 CJS 模式下具有不同的邏輯,這可能會導致一些錯位。
server.deps.cacheDir
- 類型
字串
- 預設:
'node_modules/.vite'
儲存快取檔案的目錄。
deps
- 類型:
{ optimizer?, ... }
處理相依性解析。
deps.optimizer 0.34.0+
- 類型:
{ ssr?, web? }
- 另請參閱: 相依性最佳化選項
啟用相依性最佳化。如果您有許多測試,這可能會提升其效能。在 Vitest 0.34.0 之前,它被命名為 deps.experimentalOptimizer
。
當 Vitest 遇到列在 include
中的外部函式庫時,它會使用 esbuild 將其打包成單一檔案,並作為整個模組匯入。這有幾個好處
- 匯入具有大量匯入的套件很昂貴。透過將它們打包成一個檔案,我們可以節省很多時間
- 匯入 UI 函式庫很昂貴,因為它們並非設計為在 Node.js 內部執行
- 您的
alias
設定現在在已打包的套件中受到尊重 - 測試中的程式碼執行方式更接近於它在瀏覽器中的執行方式
請注意,只有 deps.optimizer?.[mode].include
選項中的套件會被打包(某些外掛程式會自動填入此選項,例如 Svelte)。您可以在 Vite 文件中閱讀更多關於可用選項的資訊(Vitest 不支援 disable
和 noDiscovery
選項)。預設情況下,Vitest 對 jsdom
和 happy-dom
環境使用 optimizer.web
,對 node
和 edge
環境使用 optimizer.ssr
,但它可以透過 transformMode
設定。
此選項也會繼承您的 optimizeDeps
設定(對於網路,Vitest 會延伸 optimizeDeps
,對於 ssr,會延伸 ssr.optimizeDeps
)。如果您在 deps.optimizer
中重新定義 include
/exclude
選項,它會在執行測試時延伸您的 optimizeDeps
。如果 exclude
中列出了相同的選項,Vitest 會自動從 include
中移除這些選項。
提示
您將無法編輯您的 node_modules
程式碼進行除錯,因為該程式碼實際上位於您的 cacheDir
或 test.cache.dir
目錄中。如果您想使用 console.log
陳述式進行除錯,請直接編輯它或使用 deps.optimizer?.[mode].force
選項強制重新打包。
deps.optimizer.{mode}.enabled
- 類型:
boolean
- 預設值:自 Vitest 1.3.0 起為
false
啟用相依性最佳化。
警告
此選項僅適用於 Vite 4.3.2 及更高版本。
deps.web 0.34.2+
- 類型:
{ transformAssets?, ... }
當轉換模式設為 web
時,套用至外部檔案的選項。預設情況下,jsdom
和 happy-dom
使用 web
模式,而 node
和 edge
環境使用 ssr
轉換模式,因此這些選項不會影響這些環境中的檔案。
通常,node_modules
中的檔案會被外部化,但這些選項也會影響 server.deps.external
中的檔案。
deps.web.transformAssets
- 類型:
boolean
- 預設值:
true
Vitest 是否應處理資產(.png、.svg、.jpg 等)檔案,並像 Vite 在瀏覽器中那樣解析它們。
如果未指定查詢,此模組的預設匯出將等於資產的路徑。
deps.web.transformCss
- 類型:
boolean
- 預設值:
true
Vitest 是否應處理 CSS(.css、.scss、.sass 等)檔案,並像 Vite 在瀏覽器中那樣解析它們。
如果使用 css
選項停用 CSS 檔案,此選項將僅靜音 ERR_UNKNOWN_FILE_EXTENSION
錯誤。
deps.web.transformGlobPattern
- 類型:
RegExp | RegExp[]
- 預設:
[]
用於比對應轉換的外部檔案的正規表示式模式。
預設情況下,node_modules
中的檔案會被外部化且不轉換,除非它是 CSS 或資產,且對應的選項未停用。
deps.interopDefault
- 類型:
boolean
- 預設值:
true
將 CJS 模組的預設值詮釋為命名匯出。有些相依性只會綑綁 CJS 模組,且不使用 Node.js 在使用 import
語法而非 require
匯入套件時可以靜態分析的命名匯出。當在 Node 環境中使用命名匯出匯入此類相依性時,您將看到此錯誤
import { read } from 'fs-jetpack';
^^^^
SyntaxError: Named export 'read' not found. The requested module 'fs-jetpack' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export.
Vitest 沒有進行靜態分析,且無法在執行程式碼之前失敗,因此如果停用此功能,您很可能會在執行測試時看到此錯誤
TypeError: createAsyncThunk is not a function
TypeError: default is not a function
預設情況下,Vitest 假設您使用打包器來繞過此問題,且不會失敗,但如果您未處理程式碼,則可以手動停用此行為。
deps.moduleDirectories
- 類型:
string[]
- 預設值:
['node_modules']
應視為模組目錄的目錄清單。此設定選項會影響 vi.mock
的行為:當未提供工廠且您要模擬的路徑與其中一個 moduleDirectories
值相符時,Vitest 會嘗試在專案的 根目錄 中尋找 __mocks__
資料夾來解析模擬。
此選項也會影響在對外化相依性時,檔案是否應視為模組。預設情況下,Vitest 會使用原生 Node.js 匯入外部模組,繞過 Vite 轉換步驟。
設定此選項將會覆寫預設值,如果您仍希望在 node_modules
中搜尋套件,請將其與任何其他選項一起包含
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
deps: {
moduleDirectories: ['node_modules', path.resolve('../../packages')],
}
},
})
runner
- 類型:
VitestRunnerConstructor
- 預設值:執行測試時為
node
,執行基準時為benchmark
自訂測試執行器的路徑。這是一個進階功能,應與自訂函式庫執行器搭配使用。您可以在 文件 中閱讀更多相關資訊。
benchmark
- 類型:
{ include?, exclude?, ... }
執行 vitest bench
時使用的選項。
benchmark.include
- 類型:
string[]
- 預設值:
['**/*.{bench,benchmark}.?(c|m)[jt]s?(x)']
包含基準測試檔案的 glob
benchmark.exclude
- 類型:
string[]
- 預設值:
['node_modules', 'dist', '.idea', '.git', '.cache']
排除基準測試檔案的 glob
benchmark.includeSource
- 類型:
string[]
- 預設:
[]
包含來源中基準測試檔案的 glob。此選項類似於 includeSource
。
定義後,Vitest 將執行所有在其中包含 import.meta.vitest
的相符檔案。
benchmark.reporters
- 類型:
Arrayable<BenchmarkBuiltinReporters | Reporter>
- 預設值:
'default'
自訂輸出報告器。可以包含一個或多個內建報告名稱、報告器實例和/或自訂報告器的路徑。
benchmark.outputFile
- 類型:
字串 | 記錄<字串, 字串>
當 --reporter=json
選項也已指定時,將基準測試結果寫入檔案。透過提供物件而非字串,您可以在使用多個報告器時定義個別輸出。
要透過 CLI 命令提供物件,請使用下列語法:--outputFile.json=./path --outputFile.junit=./other-path
。
benchmark.outputJson 1.6.0+
- 類型:
字串 | 未定義
- 預設值:
未定義
用於儲存基準測試結果的檔案路徑,稍後可供 --compare
選項使用。
例如
# save main branch's result
git checkout main
vitest bench --outputJson main.json
# change a branch and compare against main
git checkout feature
vitest bench --compare main.json
benchmark.compare 1.6.0+
- 類型:
字串 | 未定義
- 預設值:
未定義
與目前執行比較的前次基準測試結果的檔案路徑。
別名
- 類型:
記錄<字串, 字串> | 陣列<{ 尋找:字串 | 正規表示式,替換:字串,自訂解析器:解析器函式 | 解析器物件 }>
在測試中執行時定義自訂別名。它們會與 resolve.alias
中的別名合併。
警告
Vitest 使用 Vite SSR 原語執行測試,其具有 某些陷阱。
全域
- 類型:
boolean
- 預設:
false
- CLI:
--globals
,--globals=false
預設情況下,vitest
沒有提供全域 API 以確保明確性。如果您偏好像 Jest 那樣在全域使用 API,您可以將 --globals
選項傳遞給 CLI 或在設定中新增 globals: true
。
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
},
})
若要讓 TypeScript 與全域 API 搭配使用,請將 vitest/globals
新增到 tsconfig.json
中的 types
欄位
// tsconfig.json
{
"compilerOptions": {
"types": ["vitest/globals"]
}
}
如果您已經在專案中使用 unplugin-auto-import
,您也可以直接使用它自動匯入那些 API。
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
AutoImport({
imports: ['vitest'],
dts: true, // generate TypeScript declaration
}),
],
})
環境
- 類型:
'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | 字串
- 預設值:
'node'
- CLI:
--environment=<env>
用於測試的環境。Vitest 中的預設環境是 Node.js 環境。如果您正在建置網頁應用程式,您可以透過 jsdom
或 happy-dom
使用類似瀏覽器的環境。如果您正在建置 edge 函式,可以使用 edge-runtime
環境
透過在檔案頂端新增 @vitest-environment
文件區塊或註解,您可以指定另一個環境用於該檔案中的所有測試
文件區塊樣式
/**
* @vitest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div')
expect(element).not.toBeNull()
})
註解樣式
// @vitest-environment happy-dom
test('use happy-dom in this test file', () => {
const element = document.createElement('div')
expect(element).not.toBeNull()
})
為了與 Jest 相容,也有 @jest-environment
/**
* @jest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div')
expect(element).not.toBeNull()
})
如果您以 --isolate=false
旗標執行 Vitest,您的測試將以這個順序執行:node
、jsdom
、happy-dom
、edge-runtime
、自訂環境
。這表示具有相同環境的每個測試都會分組,但仍然會依序執行。
從 0.23.0 開始,您也可以定義自訂環境。當使用非內建環境時,Vitest 會嘗試載入套件 vitest-environment-${name}
。該套件應該匯出具有 Environment
形狀的物件
import type { Environment } from 'vitest'
export default <Environment>{
name: 'custom',
transformMode: 'ssr',
setup() {
// custom setup
return {
teardown() {
// called after all tests with this env have been run
}
}
}
}
Vitest 也透過 vitest/environments
項目公開 builtinEnvironments
,以防您只想延伸它。您可以在 我們的指南 中閱讀更多關於延伸環境的資訊。
提示
從 Vitest 1.3.0 開始,jsdom 環境公開 jsdom
全域變數等於目前的 JSDOM 實例。如果您希望 TypeScript 識別它,當您使用這個環境時,您可以在 tsconfig.json
中新增 vitest/jsdom
{
"compilerOptions": {
"types": ["vitest/jsdom"]
}
}
environmentOptions
- 類型:
Record<'jsdom' | string, unknown>
- 預設值:
{}
這些選項會傳遞給目前 environment
的 setup
方法。預設情況下,您只能設定 JSDOM 選項(如果您使用它作為測試環境)。
environmentMatchGlobs
- 類型:
[string, EnvironmentName][]
- 預設:
[]
根據 glob 自動指派環境。將使用第一個符合條件的環境。
例如
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environmentMatchGlobs: [
// all tests in tests/dom will run in jsdom
['tests/dom/**', 'jsdom'],
// all tests in tests/ with .edge.test.ts will run in edge-runtime
['**\/*.edge.test.ts', 'edge-runtime'],
// ...
]
}
})
poolMatchGlobs 0.29.4+
- 類型:
[string, 'threads' | 'forks' | 'vmThreads' | 'vmForks' | 'typescript'][]
- 預設:
[]
根據 glob 自動指派測試將執行的池。將使用第一個符合條件的池。
例如
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
poolMatchGlobs: [
// all tests in "worker-specific" directory will run inside a worker as if you enabled `--pool=threads` for them,
['**/tests/worker-specific/**', 'threads'],
// run all tests in "browser" directory in an actual browser
['**/tests/browser/**', 'browser'],
// all other tests will run based on "browser.enabled" and "threads" options, if you didn't specify other globs
// ...
]
}
})
update *
- 類型:
boolean
- 預設:
false
- CLI:
-u
、--update
、--update=false
更新快照檔案。這將更新所有已變更的快照,並刪除過時的快照。
watch *
- 類型:
boolean
- 預設值:
!process.env.CI
- CLI:
-w
、--watch
、--watch=false
啟用監控模式
root
- 類型:
string
- CLI:
-r <path>
、--root=<path>
專案根目錄
reporters *
- 類型:
Reporter | Reporter[]
- 預設值:
'default'
- CLI:
--reporter=<name>
、--reporter=<name1> --reporter=<name2>
自訂 報告者 以輸出。報告者可以是 報告者實例、用於選取內建報告者的字串,或自訂實作的路徑(例如:'./path/to/reporter.ts'
、'@scope/reporter'
)。
outputFile *
- 類型:
字串 | 記錄<字串, 字串>
- CLI:
--outputFile=<路徑>
、--outputFile.json=./路徑
當 --reporter=json
、--reporter=html
或 --reporter=junit
選項也已指定時,將測試結果寫入檔案。提供物件而非字串,您可以在使用多個報告者時定義個別輸出。
pool * 1.0.0+
- 類型:
'threads' | 'forks' | 'vmThreads' | 'vmForks'
- 預設值:
'threads'
- CLI:
--pool=threads
用於執行測試的池。
threads *
使用 tinypool(Piscina 的輕量級分支)啟用多執行緒。使用執行緒時,您無法使用與處理程序相關的 API,例如 process.chdir()
。某些以原生語言編寫的函式庫,例如 Prisma、bcrypt
和 canvas
,在多個執行緒中執行時會有問題,並會遇到區段錯誤。在這些情況下,建議改用 forks
池。
forks *
與 threads
池類似,但透過 tinypool 使用 child_process
而不是 worker_threads
。測試與主處理程序之間的通訊速度不如 threads
池。forks
池中可以使用與處理程序相關的 API,例如 process.chdir()
。
vmThreads *
使用 VM 環境(在沙盒環境中)在 threads
池中執行測試。
這使得測試執行速度更快,但執行 ESM 程式碼 時,VM 模組不穩定。您的測試將會 記憶體外洩 - 為了解決此問題,請考慮手動編輯 poolOptions.vmThreads.memoryLimit
值。
警告
在沙盒中執行程式碼有一些優點(測試更快),但也有一些缺點。
- 原生模組(例如
fs
、path
等)中的全域變數與測試環境中存在的全域變數不同。因此,這些原生模組所引發的任何錯誤都會參考與您的程式碼中使用的錯誤建構函式不同的錯誤建構函式
try {
fs.writeFileSync('/doesnt exist')
}
catch (err) {
console.log(err instanceof Error) // false
}
- 匯入 ES 模組會無限期快取它們,如果您有很多環境(測試檔案),這會導致記憶體外洩。Node.js 中沒有可以清除該快取的 API。
- 在沙盒環境中存取全域變數 需要更長的時間。
使用此選項時,請注意這些問題。Vitest 團隊無法解決我們這邊的任何問題。
vmForks *
類似於 vmThreads
池,但透過 tinypool 使用 child_process
取代 worker_threads
。測試與主程序之間的通訊速度不如 vmThreads
池。vmForks
池中可以使用與程序相關的 API,例如 process.chdir()
。請注意,此池有與 vmThreads
中列出的相同缺點。
poolOptions * 1.0.0+
- 類型:
Record<'threads' | 'forks' | 'vmThreads' | 'vmForks', {}>
- 預設值:
{}
poolOptions.threads
threads
池選項。
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
poolOptions: {
threads: {
// Threads related options here
}
}
}
})
poolOptions.threads.maxThreads *
- 類型:
數字
- 預設: 可用 CPU
執行緒的最大數量。您也可以使用 VITEST_MAX_THREADS
環境變數。
poolOptions.threads.minThreads *
- 類型:
數字
- 預設: 可用 CPU
執行緒的最小數量。您也可以使用 VITEST_MIN_THREADS
環境變數。
poolOptions.threads.singleThread
- 類型:
boolean
- 預設:
false
在單一工作執行緒內使用相同的環境執行所有測試。這將停用內建的模組隔離(您的原始碼或內嵌程式碼仍會針對每個測試重新評估),但可以提升測試效能。
警告
即使此選項會強制測試一個接一個執行,此選項仍與 Jest 的 --runInBand
不同。Vitest 不僅使用工作執行緒平行執行測試,也用於提供隔離。停用此選項後,您的測試將依序執行,但會在相同的全域環境中執行,因此您必須自行提供隔離。
如果您依賴全域狀態(前端架構通常會依賴),或者您的程式碼依賴於為每個測試分別定義的環境,這可能會導致各種問題。但對於不一定要依賴全域狀態或可以輕鬆繞過全域狀態的測試,這可以提升測試速度(快達 3 倍)。
poolOptions.threads.useAtomics *
- 類型:
boolean
- 預設:
false
使用 Atomics 同步執行緒。
這可以在某些情況下提升效能,但可能會導致較舊的 Node 版本發生區段錯誤。
poolOptions.threads.isolate
- 類型:
boolean
- 預設值:
true
為每個測試檔案隔離環境。
poolOptions.threads.execArgv *
- 類型:
string[]
- 預設:
[]
在執行緒中傳遞其他引數給 node
。請參閱 命令列 API | Node.js 以取得更多資訊。
警告
使用時請小心,因為某些選項可能會導致工作執行緒崩潰,例如 --prof、--title。請參閱 https://github.com/nodejs/node/issues/41103。
poolOptions.forks
forks
池選項。
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
poolOptions: {
forks: {
// Forks related options here
}
}
}
})
poolOptions.forks.maxForks *
- 類型:
數字
- 預設: 可用 CPU
最大執行緒數。
poolOptions.forks.minForks *
- 類型:
數字
- 預設: 可用 CPU
最小執行緒數。
poolOptions.forks.isolate
- 類型:
boolean
- 預設值:
true
為每個測試檔案隔離環境。
poolOptions.forks.singleFork
- 類型:
boolean
- 預設:
false
在單一子處理程序中使用相同環境執行所有測試。這將停用內建模組隔離(您的原始程式碼或 內嵌 程式碼仍會針對每個測試重新評估),但可以提升測試效能。
警告
即使此選項會強制測試一個接一個執行,但此選項與 Jest 的 --runInBand
不同。Vitest 不僅使用子處理程序來平行執行測試,也用於提供隔離。停用此選項後,您的測試將順序執行,但會在相同的全域環境中執行,因此您必須自行提供隔離。
如果您依賴全域狀態(前端架構通常會依賴),或者您的程式碼依賴於為每個測試分別定義的環境,這可能會導致各種問題。但對於不一定要依賴全域狀態或可以輕鬆繞過全域狀態的測試,這可以提升測試速度(快達 3 倍)。
poolOptions.forks.execArgv *
- 類型:
string[]
- 預設:
[]
在子處理程序中傳遞其他引數給 node
處理程序。請參閱 命令列 API | Node.js 以取得更多資訊。
警告
使用時請小心,因為某些選項可能會導致工作執行緒崩潰,例如 --prof、--title。請參閱 https://github.com/nodejs/node/issues/41103。
poolOptions.vmThreads
vmThreads
池的選項。
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
poolOptions: {
vmThreads: {
// VM threads related options here
}
}
}
})
poolOptions.vmThreads.maxThreads *
- 類型:
數字
- 預設: 可用 CPU
執行緒的最大數量。您也可以使用 VITEST_MAX_THREADS
環境變數。
poolOptions.vmThreads.minThreads *
- 類型:
數字
- 預設: 可用 CPU
執行緒的最小數量。您也可以使用 VITEST_MIN_THREADS
環境變數。
poolOptions.vmThreads.memoryLimit *
- 類型:
字串 | 數字
- 預設值:
1 / CPU 核心
指定工作人員在回收前記憶體限制。這個值高度依賴於您的環境,因此最好手動指定它,而不是依賴預設值。
提示
實作基於 Jest 的 workerIdleMemoryLimit
。
限制可以用許多不同的方式指定,而無論結果為何,Math.floor
都用於將其轉換為整數值
<= 1
- 假設該值為系統記憶體的百分比。因此 0.5 將工作人員的記憶體限制設定為系統總記憶體的一半\> 1
- 假設為固定位元組值。由於先前的規則,如果您想要 1 位元組的值(我不知道為什麼),您可以使用 1.1。- 帶有單位
50%
- 如上所述,為系統總記憶體的百分比100KB
、65MB
等 - 帶有單位表示固定記憶體限制。K
/KB
- 千位元組 (x1000)KiB
- 基千位元組 (x1024)M
/MB
- 百萬位元組MiB
- 兆基位元組G
/GB
- 十億位元組GiB
- 吉基位元組
警告
基於百分比的記憶體限制 在 Linux CircleCI 工作人員上不起作用,因為報告了不正確的系統記憶體。
poolOptions.vmThreads.useAtomics *
- 類型:
boolean
- 預設:
false
使用 Atomics 同步執行緒。
這可以在某些情況下提升效能,但可能會導致較舊的 Node 版本發生區段錯誤。
poolOptions.vmThreads.execArgv *
- 類型:
string[]
- 預設:
[]
傳遞其他引數給 VM 背景中的 node
程序。請參閱 命令列 API | Node.js 以取得更多資訊。
警告
使用時請小心,因為某些選項可能會導致工作執行緒崩潰,例如 --prof、--title。請參閱 https://github.com/nodejs/node/issues/41103。
poolOptions.vmForks *
vmForks
池的選項。
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
poolOptions: {
vmForks: {
// VM forks related options here
}
}
}
})
poolOptions.vmForks.maxForks *
- 類型:
數字
- 預設: 可用 CPU
執行緒的最大數量。您也可以使用 VITEST_MAX_FORKS
環境變數。
poolOptions.vmForks.minForks *
- 類型:
數字
- 預設: 可用 CPU
執行緒的最小數量。您也可以使用 VITEST_MIN_FORKS
環境變數。
poolOptions.vmForks.memoryLimit *
- 類型:
字串 | 數字
- 預設值:
1 / CPU 核心
指定工作人員在回收前記憶體限制。此值高度依賴於您的環境,因此最好手動指定它,而不是依賴預設值。值的計算方式說明於 poolOptions.vmThreads.memoryLimit
poolOptions.vmForks.execArgv *
- 類型:
string[]
- 預設:
[]
傳遞其他引數給 VM 背景中的 node
程序。請參閱 命令列 API | Node.js 以取得更多資訊。
警告
使用時請小心,因為某些選項可能會導致工作執行緒崩潰,例如 --prof、--title。請參閱 https://github.com/nodejs/node/issues/41103。
fileParallelism 1.1.0+
- 類型:
boolean
- 預設值:
true
- CLI:
--no-file-parallelism
、--fileParallelism=false
是否應並行執行所有測試檔案。將此設定為 false
會將 maxWorkers
和 minWorkers
選項覆寫為 1
。
maxWorkers 1.1.0+
- 類型:
數字
執行測試時工作執行緒的最大數量。poolOptions.{threads,vmThreads}.maxThreads
/poolOptions.forks.maxForks
的優先權較高。
minWorkers 1.1.0+
- 類型:
數字
執行測試時工作執行緒的最小數量。poolOptions.{threads,vmThreads}.minThreads
/poolOptions.forks.minForks
的優先權較高。
testTimeout
- 類型:
數字
- 預設值:
5000
- CLI:
--test-timeout=5000
、--testTimeout=5000
測試的預設逾時時間(毫秒)
hookTimeout
- 類型:
數字
- 預設值:
10000
- CLI:
--hook-timeout=10000
、--hookTimeout=10000
掛勾的預設逾時時間(毫秒)
teardownTimeout *
- 類型:
數字
- 預設值:
10000
- CLI:
--teardown-timeout=5000
、--teardownTimeout=5000
Vitest 關閉時等待關閉的預設逾時時間(毫秒)
silent *
- 類型:
boolean
- 預設:
false
- CLI:
--silent
、--silent=false
測試的靜默主控台輸出
setupFiles
- 類型:
字串 | 字串陣列
設定檔案的路徑。它們會在每個測試檔案之前執行。
資訊
變更設定檔案會觸發所有測試的重新執行。
您可以在其中使用 process.env.VITEST_POOL_ID
(類似整數的字串)來區分執行緒。
提示
請注意,如果您執行 --isolate=false
,這個設定檔案會在同一個全域範圍中執行多次。這表示您會在每個測試之前存取同一個全域物件,因此請確定您不會執行超過需要的相同動作。
例如,您可能會依賴全域變數
import { config } from '@some-testing-lib'
if (!globalThis.defined) {
config.plugins = [myCoolPlugin]
computeHeavyThing()
globalThis.defined = true
}
// hooks are reset before each suite
afterEach(() => {
cleanup()
})
globalThis.resetBeforeEachTest = true
globalSetup
- 類型:
字串 | 字串陣列
相對於專案根目錄的 global 設定檔案路徑。
global 設定檔案可以匯出命名函式 `setup` 和 `teardown`,或匯出傳回 teardown 函式的 `default` 函式(範例)。
資訊
可以有多個 globalSetup 檔案。setup 和 teardown 會依序執行,teardown 則會以相反順序執行。
警告
從 Vitest 1.0.0-beta 開始,global 設定僅在至少有一個正在執行的測試時才會執行。這表示 global 設定可能會在測試檔案變更後於監控模式中開始執行(測試檔案會等到 global 設定完成後才會執行)。
請注意,global 設定會在不同的全域範圍內執行,因此您的測試無法存取在此處定義的變數。不過,從 1.0.0 開始,您可以透過 `provide` 方法將可序列化資料傳遞給測試。
export default function setup({ provide }) {
provide('wsPort', 3000)
}
import type { GlobalSetupContext } from 'vitest/node'
export default function setup({ provide }: GlobalSetupContext) {
provide('wsPort', 3000)
}
// You can also extend `ProvidedContext` type
// to have type safe access to `provide/inject` methods:
declare module 'vitest' {
export interface ProvidedContext {
wsPort: number
}
}
import { inject } from 'vitest'
inject('wsPort') === 3000
watchExclude *
- 類型:
string[]
- 預設值:
['**/node_modules/**', '**/dist/**']
- 已棄用 請使用
server.watch.ignored
要忽略觸發監控重新執行的檔案路徑的 Glob 模式。
forceRerunTriggers *
- 類型:
string[]
- 預設值:
['**/package.json/**', '**/vitest.config.*/**', '**/vite.config.*/**']
將觸發整個套件重新執行的檔案路徑的 Glob 模式。與 --changed
參數配對使用時,如果在 git diff 中找到觸發器,則會執行整個測試套件。
如果您正在測試呼叫 CLI 命令,則很有用,因為 Vite 無法建構模組圖。
test('execute a script', async () => {
// Vitest cannot rerun this test, if content of `dist/index.js` changes
await execa('node', ['dist/index.js'])
})
提示
請確保您的檔案未被 watchExclude
排除。
coverage *
您可以使用 v8
、istanbul
或 自訂涵蓋率解決方案 來收集涵蓋率。
您可以使用點號表示法提供涵蓋率選項給 CLI
npx vitest --coverage.enabled --coverage.provider=istanbul --coverage.all
警告
如果您使用點號表示法提供涵蓋率選項,請記得指定 --coverage.enabled
。在這種情況下,請勿提供單一的 --coverage
選項。
coverage.provider
- 類型:
'v8' | 'istanbul' | 'custom'
- 預設值:
'v8'
- CLI:
--coverage.provider=<provider>
使用 provider
選擇用於收集覆蓋率的工具。
coverage.enabled
- 類型:
boolean
- 預設:
false
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.enabled
,--coverage.enabled=false
啟用覆蓋率收集。可以使用 --coverage
CLI 選項覆寫。
coverage.include
- 類型:
string[]
- 預設值:
['**']
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.include=<path>
,--coverage.include=<path1> --coverage.include=<path2>
包含在覆蓋率中的檔案清單,以 glob 模式表示
coverage.extension
- 類型:
字串 | 字串陣列
- 預設值:
['.js', '.cjs', '.mjs', '.ts', '.mts', '.cts', '.tsx', '.jsx', '.vue', '.svelte', '.marko']
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.extension=<extension>
,--coverage.extension=<extension1> --coverage.extension=<extension2>
coverage.exclude
- 類型:
string[]
- 預設值
[
'coverage/**',
'dist/**',
'**/[.]**',
'packages/*/test?(s)/**',
'**/*.d.ts',
'**/virtual:*',
'**/__x00__*',
'**/\x00*',
'cypress/**',
'test?(s)/**',
'test?(-*).?(c|m)[jt]s?(x)',
'**/*{.,-}{test,spec}?(-d).?(c|m)[jt]s?(x)',
'**/__tests__/**',
'**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build}.config.*',
'**/vitest.{workspace,projects}.[jt]s?(on)',
'**/.{eslint,mocha,prettier}rc.{?(c|m)js,yml}',
]
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.exclude=<path>
,--coverage.exclude=<path1> --coverage.exclude=<path2>
從覆蓋率中排除的檔案清單,以 glob 模式表示。
此選項會覆寫所有預設選項。在新增要忽略的新模式時,請延伸預設選項
import { coverageConfigDefaults, defineConfig } from 'vitest/config'
export default defineConfig({
test: {
coverage: {
exclude: ['**/custom-pattern/**', ...coverageConfigDefaults.exclude]
},
},
})
coverage.all
- 類型:
boolean
- 預設值:
true
(自 Vitest1.0.0
起) - 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.all
,--coverage.all=false
是否將所有檔案(包括未測試的檔案)包含在報告中。
coverage.clean
- 類型:
boolean
- 預設值:
true
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.clean
,--coverage.clean=false
在執行測試之前清除覆蓋率結果
coverage.cleanOnRerun
- 類型:
boolean
- 預設值:
true
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.cleanOnRerun
,--coverage.cleanOnRerun=false
在監控重跑時清除覆蓋率報告
coverage.reportsDirectory
- 類型:
string
- 預設值:
'./coverage'
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.reportsDirectory=<path>
警告
如果啟用 coverage.clean
(預設值),Vitest 會在執行測試之前刪除此目錄。
撰寫覆蓋率報告的目錄。
若要在 HTML 報告 的輸出中預覽覆蓋率報告,此選項必須設定為 html 報告目錄的子目錄(例如 ./html/coverage
)。
coverage.reporter
- 類型:
字串 | 字串陣列 | [字串, {}][]
- 預設值:
['text', 'html', 'clover', 'json']
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.reporter=<reporter>
,--coverage.reporter=<reporter1> --coverage.reporter=<reporter2>
要使用的覆蓋率報告工具。請參閱 istanbul 文件,以取得所有報告工具的詳細清單。請參閱 @types/istanbul-reporter
,以取得有關特定報告工具選項的詳細資訊。
報告者有下列三種類型
- 單一報告者:
{ reporter: 'html' }
- 多個沒有選項的報告者:
{ reporter: ['html', 'json'] }
- 單一或多個具有報告者選項的報告者 ts
{ reporter: [ ['lcov', { 'projectRoot': './src' }], ['json', { 'file': 'coverage.json' }], ['text'] ] }
從 Vitest 1.2.0 開始,您也可以傳遞自訂涵蓋率報告者。請參閱 指南 - 自訂涵蓋率報告者 以取得更多資訊。
{
reporter: [
// Specify reporter using name of the NPM package
'@vitest/custom-coverage-reporter',
['@vitest/custom-coverage-reporter', { someOption: true }],
// Specify reporter using local path
'/absolute/path/to/custom-reporter.cjs',
['/absolute/path/to/custom-reporter.cjs', { someOption: true }],
]
}
從 Vitest 0.31.0 開始,您可以在 Vitest UI 中查看涵蓋率報告:請查看 Vitest UI 涵蓋率 以取得更多詳細資訊。
coverage.reportOnFailure 0.31.2+
- 類型:
boolean
- 預設值:
false
(自 Vitest0.34.0
起) - 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.reportOnFailure
、--coverage.reportOnFailure=false
即使測試失敗,也會產生涵蓋率報告。
coverage.allowExternal
- 類型:
boolean
- 預設:
false
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.allowExternal
、--coverage.allowExternal=false
收集 專案根目錄
以外檔案的涵蓋率。
coverage.skipFull
- 類型:
boolean
- 預設:
false
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.skipFull
、--coverage.skipFull=false
不要顯示語句、分支和函式涵蓋率為 100% 的檔案。
coverage.thresholds
涵蓋率閾值的選項
coverage.thresholds.lines
- 類型:
數字
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.thresholds.lines=<number>
程式碼行的全域閾值。請參閱 istanbul 文件 以取得更多資訊。
coverage.thresholds.functions
- 類型:
數字
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.thresholds.functions=<number>
函式的全域閾值。請參閱 istanbul 文件 以取得更多資訊。
coverage.thresholds.branches
- 類型:
數字
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.thresholds.branches=<數字>
分支的整體閾值。有關更多資訊,請參閱 istanbul 文件。
coverage.thresholds.statements
- 類型:
數字
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.thresholds.statements=<數字>
陳述式的整體閾值。有關更多資訊,請參閱 istanbul 文件。
coverage.thresholds.perFile
- 類型:
boolean
- 預設:
false
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.thresholds.perFile
、--coverage.thresholds.perFile=false
檢查每個檔案的閾值。
coverage.thresholds.autoUpdate
- 類型:
boolean
- 預設:
false
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.thresholds.autoUpdate=<布林值>
當目前的涵蓋率高於已設定的閾值時,將所有閾值 lines
、functions
、branches
和 statements
更新至組態檔。此選項有助於在涵蓋率改善時維護閾值。
coverage.thresholds.100
- 類型:
boolean
- 預設:
false
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.thresholds.100
、--coverage.thresholds.100=false
將整體閾值設定為 100。--coverage.thresholds.lines 100 --coverage.thresholds.functions 100 --coverage.thresholds.branches 100 --coverage.thresholds.statements 100
的捷徑。
coverage.thresholds[glob-pattern]
- 類型:
{ statements?: 數字 functions?: 數字 branches?: 數字 lines?: 數字 }
- 預設值:
未定義
- 適用於提供者:
'v8' | 'istanbul'
設定符合 glob 模式的檔案的閾值。
{
coverage: {
thresholds: {
// Thresholds for all files
functions: 95,
branches: 70,
// Thresholds for matching glob pattern
'src/utils/**.ts': {
statements: 95,
functions: 90,
branches: 85,
lines: 80,
},
// Files matching this pattern will only have lines thresholds set.
// Global thresholds are not inherited.
'**/math.ts': {
lines: 100,
}
}
}
}
coverage.ignoreEmptyLines
- 類型:
boolean
- 預設:
false
- 適用於提供者:
'v8'
- CLI:
--coverage.ignoreEmptyLines=<布林值>
忽略空白行、註解和其他非執行時期程式碼,例如 Typescript 類型。
此選項僅在使用的編譯器從轉譯的程式碼中移除註解和其他非執行時期程式碼時才有效。預設情況下,Vite 使用 ESBuild,它會從 .ts
、.tsx
和 .jsx
檔案中移除註解和 Typescript 類型。
如果您想將 ESBuild 套用至其他檔案,請在 esbuild
選項 中定義它們
import { defineConfig } from 'vitest/config'
export default defineConfig({
esbuild: {
// Transpile all files with ESBuild to remove comments from code coverage.
// Required for `test.coverage.ignoreEmptyLines` to work:
include: ['**/*.js', '**/*.jsx', '**/*.mjs', '**/*.ts', '**/*.tsx'],
},
test: {
coverage: {
provider: 'v8',
ignoreEmptyLines: true,
},
},
})
coverage.ignoreClassMethods
- 類型:
string[]
- 預設:
[]
- 可供供應商使用:
'istanbul'
- CLI:
--coverage.ignoreClassMethods=<method>
設定為要忽略涵蓋範圍的類別方法名稱陣列。請參閱 istanbul 文件 以取得更多資訊。
coverage.watermarks
- 類型
{
statements?: [number, number],
functions?: [number, number],
branches?: [number, number],
lines?: [number, number]
}
- 預設值
{
statements: [50, 80],
functions: [50, 80],
branches: [50, 80],
lines: [50, 80]
}
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.watermarks.statements=50,80
,--coverage.watermarks.branches=50,80
陳述、行、分支和函式的浮水印。請參閱 istanbul 文件 以取得更多資訊。
coverage.processingConcurrency
- 類型:
boolean
- 預設:
Math.min(20, os.availableParallelism?.() ?? os.cpus().length)
- 適用於提供者:
'v8' | 'istanbul'
- CLI:
--coverage.processingConcurrency=<number>
處理涵蓋範圍結果時使用的並行限制。
coverage.customProviderModule
- 類型:
string
- 可供供應商使用:
'custom'
- CLI:
--coverage.customProviderModule=<path or module name>
指定自訂涵蓋範圍供應商模組的模組名稱或路徑。請參閱 指南 - 自訂涵蓋範圍供應商 以取得更多資訊。
testNamePattern *
- 類型
字串 | RegExp
- CLI:
-t <pattern>
,--testNamePattern=<pattern>
,--test-name-pattern=<pattern>
執行與該模式相符的完整名稱的測試。如果您將 OnlyRunThis
新增至這個屬性,測試名稱中不包含字詞 OnlyRunThis
的測試將會被略過。
import { expect, test } from 'vitest'
// run
test('OnlyRunThis', () => {
expect(true).toBe(true)
})
// skipped
test('doNotRun', () => {
expect(true).toBe(true)
})
open *
- 類型:
boolean
- 預設值:
!process.env.CI
- CLI:
--open
,--open=false
開啟 Vitest UI(WIP)
api
- 類型:
布林值 | 數字
- 預設:
false
- CLI:
--api
,--api.port
,--api.host
,--api.strictPort
監聽埠並提供 API。設定為 true 時,預設埠為 51204
browser 0.29.4+
- 類型:
{ enabled?, name?, provider?, headless?, api?, slowHijackESM? }
- 預設:
{ enabled: false, headless: process.env.CI, api: 63315 }
- CLI:
--browser
、--browser=<name>
、--browser.name=chrome --browser.headless
在瀏覽器中執行 Vitest 測試。我們預設使用 WebdriverIO 來執行測試,但它可以透過 browser.provider 選項進行設定。
注意
在 指南頁面 中閱讀更多關於在真實瀏覽器中進行測試的資訊。
警告
這是一個實驗性功能。重大變更可能不會遵循 SemVer,請在使用時固定 Vitest 的版本。
browser.enabled
- 類型:
boolean
- 預設:
false
- CLI:
--browser
、--browser.enabled=false
預設在瀏覽器中執行所有測試。可以使用 poolMatchGlobs
選項覆寫。
browser.name
- 類型:
string
- CLI:
--browser=safari
在特定瀏覽器中執行所有測試。不同提供者的可用選項
webdriverio
:firefox
、chrome
、edge
、safari
playwright
:firefox
、webkit
、chromium
- 自訂:任何會傳遞給提供者的字串
browser.headless
- 類型:
boolean
- 預設:
process.env.CI
- CLI:
--browser.headless
、--browser.headless=false
在 headless
模式下執行瀏覽器。如果您在 CI 中執行 Vitest,它將預設啟用。
browser.isolate
- 類型:
boolean
- 預設值:
true
- CLI:
--browser.isolate
、--browser.isolate=false
在個別的 iframe 中執行每個測試。
browser.fileParallelism 1.3.0+
- 類型:
boolean
- 預設: 與
fileParallelism
相同 - CLI:
--browser.fileParallelism=false
同時建立所有測試 iframe,以便它們並行執行。
這使得無法使用互動式 API(例如點擊或滑鼠移入),因為螢幕上同時有多個 iframe,但如果你的測試不依賴這些 API,同時執行所有測試可能會快很多。
提示
如果你透過 browser.isolate=false
停用隔離,你的測試檔案仍會一個接一個執行,這是因為測試執行器的特性。
browser.api
- 類型:
數字 | { port?, strictPort?, host? }
- 預設值:
63315
- CLI:
--browser.api=63315
、--browser.api.port=1234, --browser.api.host=example.com
設定在瀏覽器中提供程式碼的 Vite 伺服器的選項。不會影響 test.api
選項。
browser.provider
- 類型:
'webdriverio' | 'playwright' | 字串
- 預設值:
'webdriverio'
- CLI:
--browser.provider=playwright
執行瀏覽器測試時將使用的提供者的路徑。Vitest 提供兩個提供者,分別為 webdriverio
(預設)和 playwright
。自訂提供者應使用 default
匯出,並具有此形狀
export interface BrowserProvider {
name: string
getSupportedBrowsers: () => readonly string[]
initialize: (ctx: Vitest, options: { browser: string; options?: BrowserProviderOptions }) => Awaitable<void>
openPage: (url: string) => Awaitable<void>
close: () => Awaitable<void>
}
警告
這是提供給函式庫作者的高階 API。如果你只需要在瀏覽器中執行測試,請使用 browser 選項。
browser.providerOptions 1.0.0+
- 類型:
BrowserProviderOptions
呼叫 provider.initialize
時將傳遞給提供者的選項。
export default defineConfig({
test: {
browser: {
providerOptions: {
launch: {
devtools: true,
}
}
}
}
})
提示
在使用內建提供者時,若要擁有更好的類型安全性,你可以將其中一種類型(適用於你正在使用的提供者)新增到 tsconfig 的 compilerOptions.types
欄位
{
"compilerOptions": {
"types": [
"@vitest/browser/providers/webdriverio",
"@vitest/browser/providers/playwright"
]
}
}
browser.slowHijackESM 0.31.0+
- 類型:
boolean
- 預設:
false
在 Node.js 中執行測試時,Vitest 可以使用自己的模組解析來輕鬆模擬使用 vi.mock
語法的模組。然而,在瀏覽器中複製 ES 模組解析並不容易,因此我們需要在瀏覽器使用你的原始檔之前轉換它們。
此選項對在 Node.js 中執行的測試無效。
如果您依賴於使用 vi.spyOn
偵測 ES 模組,您可以啟用此實驗性功能以允許偵測模組匯出。
browser.indexScripts 1.6.0+
- 類型:
BrowserScript[]
- 預設:
[]
在測試 iframe 初始化之前,應注入到 index HTML 中的客製化指令碼。此 HTML 文件僅設定 iframe,實際上並未匯入您的程式碼。
指令碼 src
和 content
將由 Vite 外掛程式處理。指令碼應提供以下格式
export interface BrowserScript {
/**
* If "content" is provided and type is "module", this will be its identifier.
*
* If you are using TypeScript, you can add `.ts` extension here for example.
* @default `injected-${index}.js`
*/
id?: string
/**
* JavaScript content to be injected. This string is processed by Vite plugins if type is "module".
*
* You can use `id` to give Vite a hint about the file extension.
*/
content?: string
/**
* Path to the script. This value is resolved by Vite so it can be a node module or a file path.
*/
src?: string
/**
* If the script should be loaded asynchronously.
*/
async?: boolean
/**
* Script type.
* @default 'module'
*/
type?: string
}
browser.testerScripts 1.6.0+
- 類型:
BrowserScript[]
- 預設:
[]
在測試環境初始化之前,應注入到測試人員 HTML 中的客製化指令碼。這對於注入 Vitest 瀏覽器實作所需的 polyfill 很有用。建議在幾乎所有情況下使用 setupFiles
,而不是使用此選項。
指令碼 src
和 content
將由 Vite 外掛程式處理。
clearMocks
- 類型:
boolean
- 預設:
false
將在每個測試之前對所有偵測器呼叫 .mockClear()
。這將清除偵測器記錄,但不會將其實作重設為預設值。
mockReset
- 類型:
boolean
- 預設:
false
將在每個測試之前對所有偵測器呼叫 .mockReset()
。這將清除偵測器記錄,並將其實作重設為空函式(將傳回 undefined
)。
restoreMocks
- 類型:
boolean
- 預設:
false
將在每個測試之前對所有偵測器呼叫 .mockRestore()
。這將清除偵測器記錄,並將其實作重設為原始值。
unstubEnvs 0.26.0+
- 類型:
boolean
- 預設:
false
在每個測試前呼叫 vi.unstubAllEnvs
。
unstubGlobals 0.26.0+
- 類型:
boolean
- 預設:
false
在每個測試前呼叫 vi.unstubAllGlobals
。
testTransformMode 0.34.0+
- 類型:
{ web?, ssr? }
決定與 glob 模式相符的測試中匯入的所有模組的轉換方法。預設情況下,依賴於環境。例如,具有 JSDOM 環境的測試將處理所有具有 ssr: false
標記的檔案,而具有 Node 環境的測試將處理所有具有 ssr: true
的模組。
testTransformMode.ssr
- 類型:
string[]
- 預設:
[]
對指定測試中的所有模組使用 SSR 轉換管線。
在處理這些檔案時,Vite 外掛程式將收到 ssr: true
標記。
testTransformMode.web
- 類型:
string[]
- 預設:
[]
首先執行正常的轉換管線(目標瀏覽器),然後執行 SSR 重寫以在 Node 中執行程式碼。
在處理這些檔案時,Vite 外掛程式將收到 ssr: false
標記。
snapshotFormat *
- 類型:
PrettyFormatOptions
快照測試的格式選項。這些選項傳遞給 pretty-format
。
提示
請注意,此物件上的 plugins
欄位將被忽略。
如果您需要透過 pretty-format 外掛程式來擴充快照序列化器,請使用 expect.addSnapshotSerializer
API 或 snapshotSerializers 選項。
snapshotSerializers * 1.3.0+
- 類型:
string[]
- 預設:
[]
快照測試快照序列化模組路徑清單,如果您想新增自訂快照序列化器,這會很有用。如需更多資訊,請參閱自訂序列化器。
resolveSnapshotPath *
- 類型:
(testPath: string, snapExtension: string) => string
- 預設值:將快照檔案儲存在
__snapshots__
目錄中
覆寫預設快照路徑。例如,將快照儲存在測試檔案旁邊
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
resolveSnapshotPath: (testPath, snapExtension) => testPath + snapExtension,
},
})
allowOnly
- 類型:
boolean
- 預設值:
!process.env.CI
- CLI:
--allowOnly
、--allowOnly=false
允許標示為 only 的測試和套件。
dangerouslyIgnoreUnhandledErrors *
- 類型:
boolean
- 預設值:
false
- CLI:
--dangerouslyIgnoreUnhandledErrors
--dangerouslyIgnoreUnhandledErrors=false
忽略發生的任何未處理錯誤。
passWithNoTests *
- 類型:
boolean
- 預設值:
false
- CLI:
--passWithNoTests
、--passWithNoTests=false
如果找不到任何測試,Vitest 就不會失敗。
logHeapUsage
- 類型:
boolean
- 預設值:
false
- CLI:
--logHeapUsage
、--logHeapUsage=false
在每個測試後顯示堆積使用量。對於偵錯記憶體外洩很有用。
css
- 類型:
boolean | { include?, exclude?, modules? }
設定是否要處理 CSS。排除時,CSS 檔案會被替換為空字串,以略過後續處理。CSS 模組會傳回代理,以不影響執行時間。
css.include
- 類型:
RegExp | RegExp[]
- 預設值:
[]
應傳回實際 CSS 並由 Vite 管線處理的檔案的 RegExp 樣式。
提示
若要處理所有 CSS 檔案,請使用 /.+/
。
css.exclude
- 類型:
RegExp | RegExp[]
- 預設值:
[]
將傳回空 CSS 檔案的檔案的 RegExp 樣式。
css.modules
- 類型:
{ classNameStrategy? }
- 預設值:
{}
css.modules.classNameStrategy
- 類型:
'stable' | 'scoped' | 'non-scoped'
- 預設值:
'stable'
如果您決定處理 CSS 檔案,您可以設定 CSS 模組內的類別名稱是否應為範圍化。您可以選擇下列選項之一
stable
:類別名稱將產生為_${name}_${hashedFilename}
,這表示如果 CSS 內容變更,產生的類別將保持不變,但如果檔案名稱變更或檔案移至其他資料夾,則會變更。如果您使用快照功能,此設定會很有用。scoped
:類別名稱將照常產生,尊重css.modules.generateScopeName
方法(如果您有此方法且已啟用 CSS 處理)。預設情況下,檔案名稱將產生為_${name}_${hash}
,其中雜湊包含檔案名稱和檔案內容。non-scoped
:類別名稱不會進行雜湊處理。
警告
預設情況下,Vitest 會匯出一個代理程式,繞過 CSS 模組處理。如果您依賴類別上的 CSS 屬性,則必須使用 include
選項啟用 CSS 處理。
maxConcurrency
- 類型:
數字
- 預設值:
5
- CLI:
--max-concurrency=10
、--maxConcurrency=10
標記為 test.concurrent
的同時允許執行的測試數量。
超過此限制的測試將排隊,等到有可用時段時再執行。
cache *
- 類型:
false
- CLI:
--no-cache
、--cache=false
如果您要停用快取功能,請使用此選項。目前 Vitest 會儲存測試結果的快取,以先執行較長且失敗的測試。
順序
- 類型:
{ sequencer?, shuffle?, seed?, hooks?, setupFiles? }
測試排序方式的選項。
你可以使用點號表示法提供順序選項給 CLI
npx vitest --sequence.shuffle --sequence.seed=1000
sequence.sequencer *
- 類型:
TestSequencerConstructor
- 預設值:
BaseSequencer
定義分片和排序方法的自訂類別。如果你只需要重新定義 sort
和 shard
方法中的其中一個,但兩個都必須存在,你可以從 vitest/node
延伸 BaseSequencer
。
分片發生在排序之前,而且只有在提供 --shard
選項時才會發生。
sequence.shuffle
- 類型:
boolean | { files?, tests? }
- 預設值:
false
- CLI:
--sequence.shuffle
,--sequence.shuffle=false
如果你希望檔案和測試隨機執行,你可以使用這個選項或 CLI 參數 --sequence.shuffle
來啟用它。
Vitest 通常使用快取來排序測試,因此執行時間長的測試會先開始執行 - 這會讓測試執行得更快。如果你的檔案和測試會以隨機順序執行,你將會失去這個效能提升,但這可能有助於追蹤意外依賴先前執行的其他測試的測試。
sequence.shuffle.files 1.4.0+
- 類型:
boolean
- 預設值:
false
- CLI:
--sequence.shuffle.files
,--sequence.shuffle.files=false
是否要將檔案隨機化,請注意,如果你啟用這個選項,執行時間長的測試不會先開始執行。
sequence.shuffle.tests 1.4.0+
- 類型:
boolean
- 預設值:
false
- CLI:
--sequence.shuffle.tests
,--sequence.shuffle.tests=false
是否要將測試隨機化。
sequence.concurrent 0.32.2+
- 類型:
boolean
- 預設值:
false
- CLI:
--sequence.concurrent
,--sequence.concurrent=false
如果你希望測試並行執行,你可以使用這個選項或 CLI 參數 --sequence.concurrent
來啟用它。
sequence.seed *
- 類型:
數字
- 預設值:
Date.now()
- CLI:
--sequence.seed=1000
如果測試以隨機順序執行,則設定隨機化種子。
sequence.hooks
- 類型:
'stack' | 'list' | 'parallel'
- 預設值:
'parallel'
- CLI:
--sequence.hooks=<value>
變更執行 hooks 的順序。
stack
將以反向順序排序「after」hooks,「before」hooks 將按定義順序執行list
將按定義順序排序所有 hooksparallel
將在單一群組中並行執行 hooks(父套件中的 hooks 仍會在目前套件的 hooks 之前執行)
提示
此選項不影響 onTestFinished
。它始終以反向順序呼叫。
sequence.setupFiles 0.29.3+
- 類型:
'list' | 'parallel'
- 預設值:
'parallel'
- CLI:
--sequence.setupFiles=<value>
變更執行設定檔的順序。
list
將按定義順序執行設定檔parallel
將並行執行設定檔
typecheck
設定 類型檢查 測試環境的選項。
typecheck.enabled 1.0.0+
- 類型:
boolean
- 預設值:
false
- CLI:
--typecheck
、--typecheck.enabled
在常規測試中啟用類型檢查。
typecheck.only 1.0.0+
- 類型:
boolean
- 預設值:
false
- CLI:
--typecheck.only
在啟用類型檢查時,只執行類型檢查測試。使用 CLI 時,此選項將自動啟用類型檢查。
typecheck.checker
- 類型:
'tsc' | 'vue-tsc' | string
- 預設值:
tsc
使用哪些工具進行類型檢查。Vitest 將根據類型,為特定參數產生一個程序,以便更容易解析。檢查器應實作與 tsc
相同的輸出格式。
您需要安裝套件才能使用類型檢查器
tsc
需要typescript
套件vue-tsc
需要vue-tsc
套件
您也可以傳遞自訂二進位或指令名稱的途徑,產生與 tsc --noEmit --pretty false
相同的輸出。
typecheck.include
- 類型:
string[]
- 預設值:
['**/*.{test,spec}-d.?(c|m)[jt]s?(x)']
應視為測試檔案的檔案的 Glob 模式
typecheck.exclude
- 類型:
string[]
- 預設值:
['**/node_modules/**', '**/dist/**', '**/cypress/**', '**/.{idea,git,cache,output,temp}/**']
不應視為測試檔案的檔案的 Glob 模式
typecheck.allowJs
- 類型:
boolean
- 預設值:
false
檢查有 @ts-check
註解的 JS 檔案。如果您在 tsconfig 中啟用它,這不會覆寫它。
typecheck.ignoreSourceErrors
- 類型:
boolean
- 預設值:
false
如果 Vitest 找到測試檔案以外的錯誤,不要失敗。這根本不會向您顯示非測試錯誤。
預設情況下,如果 Vitest 找到來源錯誤,它將導致測試套件失敗。
typecheck.tsconfig
- 類型:
字串
- 預設值:嘗試尋找最近的 tsconfig.json
自訂 tsconfig 的路徑,相對於專案根目錄。
slowTestThreshold *
- 類型:
數字
- 預設值:
300
- CLI:
--slow-test-threshold=<數字>
,--slowTestThreshold=<數字>
測試被視為緩慢並在結果中報告為緩慢的毫秒數。
chaiConfig 0.30.0+
- 類型:
{ includeStack?, showDiff?, truncateThreshold? }
- 預設值:
{ includeStack: false, showDiff: true, truncateThreshold: 40 }
等同於 Chai 設定。
chaiConfig.includeStack
- 類型:
boolean
- 預設:
false
影響是否將堆疊追蹤包含在斷言錯誤訊息中。預設值 false 會在錯誤訊息中隱藏堆疊追蹤。
chaiConfig.showDiff
- 類型:
boolean
- 預設值:
true
影響是否應將 showDiff
標記包含在拋出的 AssertionErrors 中。false
永遠會是 false
;當斷言要求顯示 diff 時,true
會為 true。
chaiConfig.truncateThreshold
- 類型:
數字
- 預設值:
40
設定斷言錯誤中實際值和預期值的長度閾值。如果超過此閾值,例如對於大型資料結構,則該值會被替換為類似 [ Array(3) ]
或 { Object (prop1, prop2) }
的內容。如果您想完全停用截斷,請將其設定為 0
。
此設定選項會影響 test.each
標題和斷言錯誤訊息中值的截斷。
bail 0.31.0+
- 類型:
數字
- 預設值:
0
- CLI:
--bail=<value>
在給定數量的測試失敗時停止測試執行。
預設情況下,即使某些測試案例失敗,Vitest 仍會執行所有測試案例。對於 CI 建置來說,這可能不是理想的,因為您只對 100% 成功建置有興趣,並且希望在發生測試失敗時盡快停止測試執行。bail
選項可透過在發生失敗時防止執行更多測試來加速 CI 執行。
retry 0.32.3+
- 類型:
數字
- 預設值:
0
- CLI:
--retry=<value>
如果測試失敗,則重試特定次數。
onConsoleLog *
- 類型:
(log: string, type: 'stdout' | 'stderr') => boolean | void
測試中 console.log
的自訂處理常式。如果您傳回 false
,Vitest 就不會將日誌列印至主控台。
對於過濾來自第三方程式庫的日誌很有用。
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
return !(log === 'message from third party library' && type === 'stdout')
},
},
})
onStackTrace * 1.0.0+
- 類型:
(error: Error, frame: ParsedStack) => boolean | void
處理錯誤時,套用過濾函式至每個堆疊追蹤的每個框架。第一個引數 error
是具有與標準 Error
相同屬性的物件,但它不是實際的執行個體。
對於過濾來自第三方程式庫的堆疊追蹤框架很有用。
import type { ParsedStack } from 'vitest'
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
onStackTrace(error: Error, { file }: ParsedStack): boolean | void {
// If we've encountered a ReferenceError, show the whole stack.
if (error.name === 'ReferenceError')
return
// Reject all frames from third party libraries.
if (file.includes('node_modules'))
return false
},
},
})
diff 0.34.5+
- 類型:
string
- CLI:
--diff=<value>
用於產生 diff 介面的 diff 設定檔路徑。如果你想自訂 diff 顯示,這會很有用。
import type { DiffOptions } from 'vitest'
import c from 'picocolors'
export default {
aIndicator: c.bold('--'),
bIndicator: c.bold('++'),
omitAnnotationLines: true,
} satisfies DiffOptions
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
diff: './vitest.diff.ts'
}
})
diff.truncateThreshold
- 類型:
數字
- 預設值:
0
要顯示的 diff 結果的最大長度。超過此臨界值的 diff 將會被截斷。使用預設值 0 時,截斷不會生效。
diff.truncateAnnotation
- 類型:
字串
- 預設值:
'... Diff result is truncated'
如果 diff 結果被截斷,則會在 diff 結果的結尾輸出此註解。
diff.truncateAnnotationColor
- 類型:
DiffOptionsColor = (arg: string) => string
- 預設值:
noColor = (string: string): string => string
截斷註解的顏色,預設值是無色輸出。
fakeTimers
- 類型:
FakeTimerInstallOpts
當使用 vi.useFakeTimers()
時,Vitest 會傳遞給 @sinon/fake-timers
的選項。
fakeTimers.now
- 類型:
number | Date
- 預設值:
Date.now()
使用指定的 Unix 紀元安裝假計時器。
fakeTimers.toFake
- 類型:
('setTimeout' | 'clearTimeout' | 'setImmediate' | 'clearImmediate' | 'setInterval' | 'clearInterval' | 'Date' | 'nextTick' | 'hrtime' | 'requestAnimationFrame' | 'cancelAnimationFrame' | 'requestIdleCallback' | 'cancelIdleCallback' | 'performance' | 'queueMicrotask')[]
- 預設值:
['setTimeout', 'clearTimeout', 'setImmediate', 'clearImmediate', 'setInterval', 'clearInterval', 'Date']
一個包含要偽造的全球方法和 API 名稱的陣列。
若只想要模擬 setTimeout()
和 nextTick()
,請將此屬性指定為 ['setTimeout', 'nextTick']
。
在使用 --pool=forks
透過 node:child_process
執行 Vitest 時,不支援模擬 nextTick
。NodeJS 在 node:child_process
中內部使用 process.nextTick
,並且在被模擬時會當機。在使用 --pool=threads
執行 Vitest 時,支援模擬 nextTick
。
fakeTimers.loopLimit
- 類型:
數字
- 預設值:
10_000
呼叫 vi.runAllTimers()
時將執行的最大計時器數量。
fakeTimers.shouldAdvanceTime
- 類型:
boolean
- 預設:
false
指示 @sinonjs/fake-timers 根據實際系統時間偏移自動遞增模擬時間(例如,每當實際系統時間變更 20 毫秒,模擬時間就會遞增 20 毫秒)。
fakeTimers.advanceTimeDelta
- 類型:
數字
- 預設值:
20
僅在與 shouldAdvanceTime: true
搭配使用時相關。每當實際系統時間變更 advanceTimeDelta 毫秒,就會將模擬時間遞增 advanceTimeDelta 毫秒。
fakeTimers.shouldClearNativeTimers
- 類型:
boolean
- 預設:
false
指示假計時器清除「原生」(即非假)計時器,方法是委派給它們各自的處理常式。這些計時器預設不會被清除,如果在開始假計時器工作階段之前存在計時器,可能會導致意外行為。
workspace * 1.1.0+
- 類型:
string
- CLI:
--workspace=./file.js
- 預設值:
vitest.{workspace,projects}.{js,ts,json}
靠近設定檔或根目錄
isolate 1.1.0+
- 類型:
boolean
- 預設值:
true
- CLI:
--no-isolate
、--isolate=false
在隔離環境中執行測試。此選項不會影響 vmThreads
和 vmForks
池。
如果您的程式碼不依賴副作用(通常對於使用 node
環境的專案而言為真),停用此選項可能會 提升效能。
提示
您可以使用 poolOptions
屬性停用特定池的隔離。
includeTaskLocation 1.4.0+
- 類型:
boolean
- 預設:
false
當 Vitest API 在 reporters 中收到任務時,是否應包含 location
屬性。如果您有大量的測試,這可能會導致效能略微下降。
location
屬性具有與原始檔案中的 test
或 describe
位置對應的 column
和 line
值。
提示
如果您不使用依賴此項的客製化程式碼,此選項不會有任何效果。
snapshotEnvironment 1.6.0+
- 類型:
string
自訂快照環境實作的路徑。如果您在不支援 Node.js API 的環境中執行測試,這會很有用。此選項對瀏覽器執行器沒有任何效果。
此物件應具有 SnapshotEnvironment
的形狀,並用於解析和讀取/寫入快照檔案
export interface SnapshotEnvironment {
getVersion: () => string
getHeader: () => string
resolvePath: (filepath: string) => Promise<string>
resolveRawPath: (testPath: string, rawPath: string) => Promise<string>
saveSnapshotFile: (filepath: string, snapshot: string) => Promise<void>
readSnapshotFile: (filepath: string) => Promise<string | null>
removeSnapshotFile: (filepath: string) => Promise<void>
}
如果您只需要覆寫 API 的一部分,您可以從 vitest/snapshot
入口點延伸預設的 VitestSnapshotEnvironment
。
警告
這是一個低階選項,僅應在您無法存取預設 Node.js API 的進階情況下使用。
如果您只需要設定快照功能,請使用 snapshotFormat
或 resolveSnapshotPath
選項。