Skip to content
Vitest 2
Main Navigation 指南API配置瀏覽器模式高級
3.2.0
2.1.9
1.6.1
0.34.6

繁體中文

English
简体中文
Español
Français
Русский
Português – Brasil
Deutsch
日本語
한국어
Italiano
Polski
Türkçe
čeština
magyar

繁體中文

English
简体中文
Español
Français
Русский
Português – Brasil
Deutsch
日本語
한국어
Italiano
Polski
Türkçe
čeština
magyar

外觀

Sidebar Navigation

管理 Vitest 配置文件

配置 Vitest

本頁導覽

配置 Vitest ​

要建立 Vitest 設定檔,請參考本指南。在繼續之前,請務必先了解 Vitest 設定解析的運作方式。

WARNING

此處列出的所有選項都位於設定中的 test 屬性裡:

ts
export default defineConfig({
  test: {
    exclude: [],
  },
});

TIP

除了以下選項外,您還可以使用 Vite 中的任何配置選項。例如,使用 define 定義全域變量,或使用 resolve.alias 定義別名。

工作區專案設定中不支援的所有配置選項旁邊都有 * 符號。

include ​

  • 類型: string[]
  • 預設值: ['**/*.{test,spec}.?(c|m)[jt]s?(x)']
  • CLI: vitest [...include], vitest **/*.test.js

符合測試檔案的 glob 模式清單。

注意

如果使用 coverage,Vitest 會自動將測試檔案的 include 模式加入到 coverage 的預設 exclude 模式中。請參閱 coverage.exclude。

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 模式清單。

WARNING

此選項不影響測試覆蓋率。如果您需要從覆蓋率報告中移除某些檔案,請使用 coverage.exclude。

如果您透過 CLI 標記提供此選項,這是唯一不會覆寫您設定的選項。透過 --exclude 標記新增的所有 glob 模式,都會新增至設定的 exclude。

includeSource ​

  • 類型: string[]
  • 預設值: []

用於原始碼內測試檔案的包含 glob 模式。

定義後,Vitest 會執行所有包含 import.meta.vitest 的相符檔案。

server ​

  • 類型: { 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 ​

  • 類型: (string | 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 一律檢查檔案路徑,而不是實際的套件名稱。

如果使用 regexp,Vitest 會在檔案路徑上呼叫它,而非套件名稱。

server.deps.inline ​

  • 類型: (string | RegExp)[] | true
  • 預設值: []

Vite 會處理內嵌模組。這可能有助於處理以 ESM 格式發布 .js 的套件 (Node 無法直接處理)。

如果為 true,則每個依賴項都會內嵌。預設會內嵌 ssr.noExternal 中指定的所有依賴項。

server.deps.fallbackCJS ​

  • 類型 boolean
  • 預設值: false

當依賴項是有效的 ESM 套件時,請嘗試根據路徑推測 cjs 版本。如果依賴項包含錯誤的 ESM 檔案,這可能會有所幫助,特別是當依賴項具有錯誤的 ESM 檔案時。

如果套件在 ESM 和 CJS 模式下有不同的邏輯,這可能會導致一些不一致的情況。

server.deps.cacheDir ​

  • 類型 string
  • 預設值:'node_modules/.vite'

儲存快取檔案的目錄。

deps ​

  • 類型: { optimizer?, ... }

處理依賴項解析。

deps.optimizer ​

  • 類型: { ssr?, web? }
  • 另請參閱: 相依性最佳化選項

啟用依賴項最佳化。如果您有很多測試,這可能會提高其效能。

當 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 設定進行擴展 (對於 web,Vitest 將擴充 optimizeDeps,對於 ssr - ssr.optimizeDeps)。如果您在 deps.optimizer 中重新定義 include/exclude 選項,它將在執行測試時擴充您的 optimizeDeps。如果 Vitest 在 exclude 中列出相同的選項,則會自動從 include 中移除它們。

TIP

您將無法編輯 node_modules 程式碼來進行除錯,因為程式碼實際上位於您的 cacheDir 或 test.cache.dir 目錄裡。如果您想要使用 console.log 陳述式進行除錯,請直接編輯它或使用 deps.optimizer?.[mode].force 選項強制重新打包。

deps.optimizer.{mode}.enabled ​

  • 類型: boolean
  • 預設值: false

啟用依賴項最佳化。

deps.web ​

  • 類型: { transformAssets?, ... }

當轉換模式設定為 web 時,套用至外部檔案的選項。依預設,jsdom 和 happy-dom 使用 web 模式,而 node 和 edge 環境使用 ssr 轉換模式,因此這些選項不會影響這些環境裡的檔案。

通常,node_modules 裡的檔案會外部化,但這些選項也會影響 server.deps.external 中的檔案。

deps.web.transformAssets ​

  • 類型: boolean
  • 預設值: true

Vitest 是否應處理資產 (.png、.svg、.jpg 等) 檔案,並像 Vite 在瀏覽器中一樣解析它們。

如果未指定查詢,則此模組將具有等於資產路徑的預設匯出。

WARNING

目前,此選項僅適用於 vmThreads 和 vmForks 集區。

deps.web.transformCss ​

  • 類型: boolean
  • 預設值: true

Vitest 是否應處理 CSS (.css、.scss、.sass 等) 檔案,並像 Vite 在瀏覽器中一樣解析它們。

如果使用 css 選項停用 CSS 檔案,此選項只會讓 ERR_UNKNOWN_FILE_EXTENSION 錯誤靜音。

WARNING

目前,此選項僅適用於 vmThreads 和 vmForks 集區。

deps.web.transformGlobPattern ​

  • 類型: RegExp | RegExp[]
  • 預設值: []

用於匹配應轉換的外部檔案的 Regexp 模式。

依預設,node_modules 裡的檔案會外部化且不會轉換,除非它是 CSS 或資產,且未停用對應的選項。

WARNING

目前,此選項僅適用於 vmThreads 和 vmForks 集區。

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 的行為:當未提供 factory 且您要模擬的內容的路徑符合其中一個 moduleDirectories 值時,Vitest 將嘗試透過在專案的 root 中尋找 __mocks__ 資料夾來解析模擬。

當外部化依賴項時,此選項也會影響檔案是否應被視為模組。依預設,Vitest 會使用原生 Node.js 匯入外部模組,繞過 Vite 轉換步驟。

設定此選項會覆寫預設值。如果您希望仍然搜尋 node_modules 以尋找套件,請將其與任何其他選項一起包含:

ts
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)']

基準測試檔案的 Include globs

benchmark.exclude ​

  • 類型: string[]
  • 預設值: ['node_modules', 'dist', '.idea', '.git', '.cache']

基準測試檔案的 Exclude globs

benchmark.includeSource ​

  • 類型: string[]
  • 預設值: []

來源程式碼內基準測試檔案的 Include globs。此選項與 includeSource 類似。

定義後,Vitest 會執行所有包含 import.meta.vitest 的相符檔案。

benchmark.reporters ​

  • 類型: Arrayable<BenchmarkBuiltinReporters | Reporter>
  • 預設值: 'default'

用於輸出的自訂報告器。可以包含一個或多個內建報告名稱、報告器實例和/或自訂報告器的路徑。

benchmark.outputFile ​

已棄用,請改用 benchmark.outputJson。

benchmark.outputJson ​

  • 類型: string | undefined
  • 預設值: undefined

儲存基準測試結果的檔案路徑,稍後可用於 --compare 選項。

例如:

sh
# 儲存主要分支的結果
git checkout main
vitest bench --outputJson main.json

# 變更分支並與主要分支比較
git checkout feature
vitest bench --compare main.json

benchmark.compare ​

  • 類型: string | undefined
  • 預設值: undefined

先前基準測試結果的檔案路徑,用於與當前執行進行比較。

alias ​

  • 類型: Record<string, string> | Array<{ find: string | RegExp, replacement: string, customResolver?: ResolverFunction | ResolverObject }>

在測試中執行時定義自訂別名。它們將與 resolve.alias 中的別名合併。

WARNING

Vitest 使用 Vite SSR 原始元件來執行測試,這具有某些缺點。

  1. 別名僅影響由 內聯 模組 (預設會內聯所有原始碼) 使用 import 關鍵字直接匯入的模組。
  2. Vitest 不支援別名化 require 呼叫。
  3. 如果您要為外部相依性建立別名 (例如,react -> preact),您可能需要為實際的 node_modules 套件建立別名,使其適用於外部化的相依性。Yarn 和 pnpm 都支援透過 npm: 前置詞進行別名化。

globals ​

  • 類型: boolean
  • 預設值: false
  • CLI: --globals, --globals=false

依預設,vitest 不提供全域 API,以提高程式碼的明確性。如果您偏好像 Jest 一樣全域使用 API,您可以將 --globals 選項傳遞至 CLI 或在設定中新增 globals: true。

ts
// vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
  },
});

若要讓 TypeScript 搭配全域 API 運作,請將 vitest/globals 加入 tsconfig.json 中的 types 欄位。

json
// tsconfig.json
{
  "compilerOptions": {
    "types": ["vitest/globals"]
  }
}

如果您已在專案中使用 unplugin-auto-import,您也可以直接使用它來自動匯入這些 API。

ts
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import AutoImport from 'unplugin-auto-import/vite';

export default defineConfig({
  plugins: [
    AutoImport({
      imports: ['vitest'],
      dts: true, // 產生 TypeScript 宣告
    }),
  ],
});

environment ​

  • Type: 'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | string
  • Default: 'node'
  • CLI: --environment=<env>

測試所使用的環境。Vitest 的預設環境是 Node.js 環境。如果您正在開發 Web 應用程式,可以使用 jsdom 或 happy-dom 來模擬瀏覽器執行環境。如果您正在構建邊緣函數,可以使用 edge-runtime 環境。

TIP

你也可以使用瀏覽器模式在瀏覽器中運行整合或單元測試,而無需模擬環境。

您可以透過在檔案頂部添加 @vitest-environment docblock 或註解,為該檔案中的所有測試指定不同的環境:

Docblock 樣式:

js
/**
 * @vitest-environment jsdom
 */

test('use jsdom in this test file', () => {
  const element = document.createElement('div');
  expect(element).not.toBeNull();
});

註解樣式:

js
// @vitest-environment happy-dom

test('use happy-dom in this test file', () => {
  const element = document.createElement('div');
  expect(element).not.toBeNull();
});

為了與 Jest 兼容,也支援 @jest-environment:

js
/**
 * @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、custom environments (自訂環境)。這表示相同環境的測試會被分組,但仍會依序執行。

從 0.23.0 開始,您還可以定義自訂環境。當使用非內建環境時,Vitest 會嘗試載入 vitest-environment-${name} 套件。該套件應匯出一個具有 Environment 結構的物件:

ts
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,方便您擴充。您可以在 我們的指南 中閱讀更多關於擴充環境的資訊。

TIP

jsdom 環境公開了 jsdom 全域變數,該變數等於當前的 JSDOM 實例。如果您希望 TypeScript 識別它,可以在使用此環境時將 vitest/jsdom 添加到您的 tsconfig.json 中:

json
{
  "compilerOptions": {
    "types": ["vitest/jsdom"]
  }
}

environmentOptions ​

  • Type: Record<'jsdom' | string, unknown>
  • Default: {}

這些選項會傳遞到當前 environment 的 setup 方法。預設情況下,如果您使用 JSDOM 作為測試環境,則只能配置 JSDOM 選項。

environmentMatchGlobs ​

  • Type: [string, EnvironmentName][]
  • Default: []

根據 glob 模式自動分配環境。將使用第一個匹配項。

例如:

ts
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 ​

  • Type: [string, 'threads' | 'forks' | 'vmThreads' | 'vmForks' | 'typescript'][]
  • Default: []

根據 glob 模式自動分配測試將在其中運行的池(pool)。將使用第一個匹配項。

例如:

ts
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* ​

  • Type: boolean
  • Default: false
  • CLI: -u, --update, --update=false

更新所有變更的快照,並刪除過時的快照。

watch* ​

  • Type: boolean
  • Default: !process.env.CI
  • CLI: -w, --watch, --watch=false

啟用監視模式。

root ​

  • Type: string
  • CLI: -r <path>, --root=<path>

專案根目錄。

dir ​

  • 類型: string
  • CLI: --dir=<path>
  • 預設值: 同 root

掃描測試檔案的基礎目錄。如果你的根目錄涵蓋了整個專案,你可以指定此選項來加快測試發現的速度。

reporters* ​

  • Type: Reporter | Reporter[]
  • Default: 'default'
  • CLI: --reporter=<name>, --reporter=<name1> --reporter=<name2>

用於輸出的自訂 報告器。報告器可以是 Reporter 實例、用於選擇內建報告器的字串,或指向自定義實現的路徑(例如 './path/to/reporter.ts', '@scope/reporter')。

outputFile* ​

  • Type: string | Record<string, string>
  • CLI: --outputFile=<path>, --outputFile.json=./path

當同時指定 --reporter=json、--reporter=html 或 --reporter=junit 選項時,將測試結果寫入檔案。 透過提供物件而不是字串,您可以在使用多個報告器時定義單獨的輸出。

pool* ​

  • Type: 'threads' | 'forks' | 'vmThreads' | 'vmForks'
  • Default: 'forks'
  • CLI: --pool=threads

用於運行測試的池。

threads* ​

使用 tinypool(Piscina 的輕量級分支)啟用多線程。使用線程時,您無法使用與進程相關的 API,例如 process.chdir()。一些用原生語言編寫的庫,例如 Prisma、bcrypt 和 canvas,在多個線程中運行時會出現問題並導致分段錯誤。在這些情況下,建議改用 forks 池。

forks* ​

與 threads 池類似,但透過 tinypool 使用 child_process 而不是 worker_threads。測試與主進程間的通訊不如 threads 池快。與進程相關的 API(例如 process.chdir())在 forks 池中可用。

vmThreads* ​

在 threads 池中使用 VM 上下文(在沙箱環境中)運行測試。

這使得測試運行速度更快,但 VM 模組在運行 ESM 代碼 時不穩定。您的測試可能會發生記憶體洩漏 - 為了解決這個問題,請考慮手動編輯 poolOptions.vmThreads.memoryLimit 值。

WARNING

在沙箱中運行代碼有一些優點(更快的測試),但也帶來了一些缺點。

  • 原生模組中的全域變數(例如 fs、path 等)與測試環境中存在的全域變數不同。因此,這些原生模組拋出的任何錯誤都將引用與您的代碼中使用的錯誤構造函數不同的錯誤構造函數:
ts
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 池快。與進程相關的 API(例如 process.chdir())在 vmForks 池中可用。請注意,此池具有與 vmThreads 中列出的相同缺陷。

poolOptions* ​

  • Type: Record<'threads' | 'forks' | 'vmThreads' | 'vmForks', {}>
  • Default: {}

poolOptions.threads ​

threads 池的選項。

ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    poolOptions: {
      threads: {
        // Threads related options here
      },
    },
  },
});
poolOptions.threads.maxThreads* ​
  • 類型: number | string
  • 預設值: 可用 CPU 數量

執行緒的最大數量或百分比。您也可以使用環境變數 VITEST_MAX_THREADS。

poolOptions.threads.minThreads* ​
  • 類型: number | string
  • 預設值: 可用 CPU 數量

執行緒的最小數量或百分比。您也可以使用環境變數 VITEST_MIN_THREADS。

poolOptions.threads.singleThread ​
  • Type: boolean
  • Default: false

在單個 worker 線程中運行具有相同環境的所有測試。這將禁用內建的模組隔離(您的原始碼或 內聯 代碼仍將為每個測試重新評估),但可以提高測試效能。

WARNING

即使此選項將強制測試一個接一個地運行,但此選項與 Jest 的 --runInBand 不同。Vitest 使用 worker 不僅僅是為了並行運行測試,而且還為了提供隔離。透過禁用此選項,您的測試將按順序運行,但在相同的全域上下文中運行,因此您必須自己提供隔離。

如果您依賴全域狀態(前端框架通常有此依賴)或您的代碼依賴於為每個測試單獨定義的環境,這可能導致各種問題。但對於那些不一定依賴全域狀態或可以輕鬆繞過它的測試來說,這可以提高測試速度(最高可快 3 倍)。

poolOptions.threads.useAtomics* ​
  • Type: boolean
  • Default: false

使用 Atomics 來同步線程。

在某些情況下,這可以提高效能,但可能會在較舊的 Node 版本中導致分段錯誤。

poolOptions.threads.isolate ​
  • Type: boolean
  • Default: true

為每個測試檔案隔離環境。

poolOptions.threads.execArgv* ​
  • Type: string[]
  • Default: []

在線程中將其他參數傳遞給 node。有關更多資訊,請參閱 Command-line API | Node.js。

WARNING

使用時請小心,因為某些選項可能會導致 worker 崩潰,例如 --prof、--title。請參閱 https://github.com/nodejs/node/issues/41103。

poolOptions.forks ​

forks 池的選項。

ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    poolOptions: {
      forks: {
        // Forks related options here
      },
    },
  },
});
poolOptions.forks.maxForks* ​
  • 類型: number | string
  • 預設值: 可用 CPU 數量

最大佇列數或百分比。

poolOptions.forks.minForks* ​
  • 類型: number | string
  • 預設值: 可用 CPU 數量

最小佇列數或百分比。

poolOptions.forks.isolate ​
  • Type: boolean
  • Default: true

為每個測試檔案隔離環境。

poolOptions.forks.singleFork ​
  • Type: boolean
  • Default: false

在單個子進程中運行具有相同環境的所有測試。這將禁用內建的模組隔離(您的原始碼或 內聯 代碼仍將為每個測試重新評估),但可以提高測試效能。

WARNING

即使此選項將強制測試一個接一個地運行,但此選項與 Jest 的 --runInBand 不同。Vitest 使用子進程不僅僅是為了並行運行測試,而且還為了提供隔離。透過禁用此選項,您的測試將按順序運行,但在相同的全域上下文中運行,因此您必須自己提供隔離。

如果您依賴全域狀態(前端框架通常有此依賴)或您的代碼依賴於為每個測試單獨定義的環境,這可能導致各種問題。但對於那些不一定依賴全域狀態或可以輕鬆繞過它的測試來說,這可以提高測試速度(最高可快 3 倍)。

poolOptions.forks.execArgv* ​
  • Type: string[]
  • Default: []

在子進程中傳遞其他參數至 node 進程。有關更多資訊,請參閱 Command-line API | Node.js。

WARNING

使用時請小心,因為某些選項可能會導致 worker 崩潰,例如 --prof、--title。請參閱 https://github.com/nodejs/node/issues/41103。

poolOptions.vmThreads ​

vmThreads 池的選項。

ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    poolOptions: {
      vmThreads: {
        // VM threads related options here
      },
    },
  },
});
poolOptions.vmThreads.maxThreads* ​
  • 類型: number | string
  • 預設值: 可用 CPU 核心數

執行緒的最大數量或百分比。你也可以使用 VITEST_MAX_THREADS 環境變數。

poolOptions.vmThreads.minThreads* ​
  • 類型: number | string
  • 預設值: 可用 CPU 核心數

執行緒的最小數量或百分比。你也可以使用 VITEST_MIN_THREADS 環境變數。

poolOptions.vmThreads.memoryLimit* ​
  • Type: string | number
  • Default: 1 / CPU Cores

指定 worker 在回收前的記憶體上限。此數值很大程度取決於您的環境,因此建議手動指定,而非依賴預設值。計算方式請參考 poolOptions.vmThreads.memoryLimit 的說明。

TIP

該實現基於 Jest 的 workerIdleMemoryLimit。

限制可以用多種不同的方式指定,無論結果如何,都使用 Math.floor 將其轉換為整數值:

  • <= 1 - 該值被假定為系統記憶體的百分比。因此,0.5 將 worker 的記憶體限制設定為總系統記憶體的一半

  • \> 1 - 假定為固定位元組值。由於之前的規則,如果您想要 1 個位元組的值(我不知道為什麼),您可以使用 1.1。

  • 帶有單位

    • 50% - 如上所述,佔系統總記憶體的百分比

    • 100KB、65MB 等 - 帶有單位表示固定記憶體限制。

      • K / KB - 千位元組 (x1000)
      • KiB - Kibibytes (x1024)
      • M / MB - 兆位元組
      • MiB - Mebibytes
      • G / GB - 吉位元組
      • GiB - Gibibytes

WARNING

由於報告的系統記憶體不正確,基於百分比的記憶體限制 在 Linux CircleCI worker 上不起作用。

poolOptions.vmThreads.useAtomics* ​
  • Type: boolean
  • Default: false

使用 Atomics 來同步線程。

在某些情況下,這可以提高效能,但可能會在較舊的 Node 版本中導致分段錯誤。

poolOptions.vmThreads.execArgv* ​
  • Type: string[]
  • Default: []

在 VM 上下文中將其他參數傳遞給 node 進程。有關更多資訊,請參閱 Command-line API | Node.js。

WARNING

使用時請小心,因為某些選項可能會導致 worker 崩潰,例如 --prof、--title。請參閱 https://github.com/nodejs/node/issues/41103。

poolOptions.vmForks ​

vmForks 池的選項。

ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    poolOptions: {
      vmForks: {
        // VM forks related options here
      },
    },
  },
});
poolOptions.vmForks.maxForks* ​
  • 類型: number | string
  • 預設值: 可用 CPU 數量

最大執行緒數或執行緒百分比。您也可以使用 VITEST_MAX_FORKS 環境變數。

poolOptions.vmForks.minForks* ​
  • 類型: number | string
  • 預設值: 可用 CPU 數量

最小執行緒數或執行緒百分比。您也可以使用 VITEST_MIN_FORKS 環境變數。

poolOptions.vmForks.memoryLimit* ​
  • Type: string | number
  • Default: 1 / CPU Cores

指定 worker 在回收前的記憶體上限。此數值很大程度取決於您的環境,因此建議手動指定,而非依賴預設值。計算方式請參考 poolOptions.vmThreads.memoryLimit 的說明。

poolOptions.vmForks.execArgv* ​
  • Type: string[]
  • Default: []

在 VM 上下文中將其他參數傳遞給 node 進程。有關更多資訊,請參閱 Command-line API | Node.js。

WARNING

使用時請小心,因為某些選項可能會導致 worker 崩潰,例如 --prof、--title。請參閱 https://github.com/nodejs/node/issues/41103。

fileParallelism* ​

  • 類型: boolean
  • 預設值: true
  • CLI: --no-file-parallelism, --fileParallelism=false

是否應平行執行所有測試檔案。 設定為 false 會覆寫 maxWorkers 和 minWorkers 選項,並將其設為 1。

TIP

此選項不影響在同一個檔案中執行的測試。 如果您想並行執行這些測試,請在 describe 中使用 concurrent 選項,或透過 配置 進行設定。

maxWorkers* ​

  • Type: number | string

執行測試的最大工作執行緒數量。poolOptions.{threads,vmThreads}.maxThreads/poolOptions.forks.maxForks 具有更高的優先權。

minWorkers* ​

  • Type: number | string

執行測試的最小工作執行緒數量或百分比。poolOptions.{threads,vmThreads}.minThreads/poolOptions.forks.minForks 具有更高的優先權。

testTimeout ​

  • Type: number
  • Default: 在 Node.js 中為 5_000,如果 browser.enabled 為 true 則為 15_000。
  • CLI: --test-timeout=5000, --testTimeout=5000

測試的預設逾時時間(毫秒)

hookTimeout ​

  • Type: number
  • Default: 在 Node.js 中為 10_000,如果 browser.enabled 為 true 則為 30_000。
  • CLI: --hook-timeout=10000, --hookTimeout=10000

鉤子的預設逾時時間(毫秒)

teardownTimeout* ​

  • 類型: number
  • 預設值: 10000
  • CLI: --teardown-timeout=5000, --teardownTimeout=5000

Vitest 關閉時,等待關閉程序的預設逾時時間(以毫秒為單位)。

silent* ​

  • 類型: boolean
  • 預設值: false
  • CLI: --silent, --silent=false

靜默測試的控制台輸出。

setupFiles ​

  • 類型: string | string[]

設定檔的路徑:

INFO

編輯 setup 檔案將自動觸發所有測試的重新執行。

您可以使用 process.env.VITEST_POOL_ID (類似整數的字串) 來區分不同的執行緒。

TIP

請注意,如果您正在執行 --isolate=false,此設定檔案將在相同的全域範圍內多次執行。 這表示您在每次測試之前都在存取相同的全域物件,因此請確保您沒有做超過必要的相同操作。

例如,您可以依賴全域變數:

ts
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;

provide 2.1.0+ ​

  • Type: Partial<ProvidedContext>

使用 inject 方法定義可以在測試中存取的值。

ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    provide: {
      API_KEY: '123',
    },
  },
});
ts
import { expect, inject, test } from 'vitest';

test('api key is defined', () => {
  expect(inject('API_KEY')).toBe('123');
});

WARNING

屬性必須是字串,並且值需要是 可序列化的,因為此物件將在不同進程之間傳輸。

TIP

如果您使用 TypeScript,您將需要擴充 ProvidedContext 類型以進行類型安全存取:

ts
// vitest.shims.d.ts

declare module 'vitest' {
  export interface ProvidedContext {
    API_KEY: string;
  }
}

// mark this file as a module so augmentation works correctly
export {};

globalSetup ​

  • 類型: string | string[]

全域設定檔的路徑,相對於專案根目錄。

全域設定檔案可以匯出具名函式 setup 和 teardown,或匯出一個返回 teardown 函式的 default 函式 (範例)。

INFO

可設定多個 globalSetup 設定檔。 setup 和 teardown 會依序執行,teardown 的執行順序相反。

WARNING

全局 setup 僅在至少有一個正在執行的測試時才會執行。這意味著全局 setup 可能會在監看模式下,在測試檔案變更後開始執行(測試檔案將等待全局 setup 完成後再執行)。

請注意,全局 setup 執行在不同的全局作用域中,因此你的測試無法存取在此定義的變數。但是,你可以透過 provide 方法將可序列化的資料傳遞給測試:

js
export default function setup({ provide }) {
  provide('wsPort', 3000);
}
ts
import type { GlobalSetupContext } from 'vitest/node';

export default function setup({ provide }: GlobalSetupContext) {
  provide('wsPort', 3000);
}

declare module 'vitest' {
  export interface ProvidedContext {
    wsPort: number;
  }
}
ts
import { inject } from 'vitest';

inject('wsPort') === 3000;

forceRerunTriggers* ​

  • 類型: string[]
  • 預設值: ['**/package.json/**', '**/vitest.config.*/**', '**/vite.config.*/**']

將觸發整個測試套件重新執行的檔案路徑的 Glob 模式。 與 --changed 參數搭配使用時,如果在 git diff 中找到觸發器,將執行整個測試套件。

如果您正在測試呼叫 CLI 命令,這會很有用,因為 Vite 無法建構模組圖:

ts
test('execute a script', async () => {
  // Vitest cannot rerun this test, if content of `dist/index.js` changes
  await execa('node', ['dist/index.js']);
});

TIP

請確認您的檔案未被 server.watch.ignored 排除。

coverage* ​

您可以使用 v8、istanbul 或 自訂覆蓋率解決方案 來收集覆蓋率。

您可以使用點表示法將覆蓋率選項提供給 CLI:

sh
npx vitest --coverage.enabled --coverage.provider=istanbul --coverage.all

WARNING

如果您使用帶有點表示法的覆蓋率選項,請不要忘記指定 --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 ​

  • 類型: string | string[]
  • 預設值: ['.js', '.cjs', '.mjs', '.ts', '.mts', '.tsx', '.jsx', '.vue', '.svelte', '.marko', '.astro']
  • 適用於提供者: 'v8' | 'istanbul'
  • CLI: --coverage.extension=<extension>, --coverage.extension=<extension1> --coverage.extension=<extension2>

coverage.exclude ​

  • 類型: string[]
  • 預設值:
js
[
  'coverage/**',
  'dist/**',
  '**/node_modules/**',
  '**/[.]**',
  'packages/*/test?(s)/**',
  '**/*.d.ts',
  '**/virtual:*',
  '**/__x00__*',
  '**/\x00*',
  'cypress/**',
  'test?(s)/**',
  'test?(-*).?(c|m)[jt]s?(x)',
  '**/*{.,-}{test,spec,bench,benchmark}?(-d).?(c|m)[jt]s?(x)',
  '**/__tests__/**',
  '**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.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 模式表示。

此選項會覆蓋所有預設選項。 在新增要忽略的新模式時,請擴展預設選項:

ts
import { coverageConfigDefaults, defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    coverage: {
      exclude: ['**/custom-pattern/**', ...coverageConfigDefaults.exclude],
    },
  },
});

注意

Vitest 會自動將測試檔案 include 模式新增至 coverage.exclude 的預設值中。

coverage.all ​

  • 類型: boolean
  • 預設值: true
  • 適用於提供者: '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

在監看模式重新執行時清除程式碼涵蓋率報告。設定為 false 以保留監看模式先前執行程式碼涵蓋率結果。

coverage.reportsDirectory ​

  • 類型: string
  • 預設值: './coverage'
  • 適用於提供者: 'v8' | 'istanbul'
  • CLI: --coverage.reportsDirectory=<path>

WARNING

如果啟用了 coverage.clean (預設值),Vitest 將在執行測試之前刪除此目錄。

用於寫入覆蓋率報告的目錄:

若要在 HTML 報告器 的輸出中預覽覆蓋率報告,則必須將此選項設定為 HTML 報告目錄的子目錄 (例如 ./html/coverage)。

coverage.reporter ​

  • 類型: string | string[] | [string, {}][]
  • 預設值: ['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'],
      ];
    }

您也可以傳遞自訂覆蓋率報告器。有關更多資訊,請參閱指南 - 自訂覆蓋率報告器。

ts
{
  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 UI 中查看你的覆蓋率報告:查看 Vitest UI 覆蓋率 獲取更多詳情。

coverage.reportOnFailure ​

  • 類型: boolean
  • 預設值: false
  • 適用於提供者: 'v8' | 'istanbul'
  • CLI: --coverage.reportOnFailure, --coverage.reportOnFailure=false

即使測試失敗也產生覆蓋率報告。

coverage.allowExternal ​

  • 類型: boolean
  • 預設值: false
  • 適用於提供者: 'v8' | 'istanbul'
  • CLI: --coverage.allowExternal, --coverage.allowExternal=false

收集 專案 root 之外的檔案的覆蓋率。

coverage.excludeAfterRemap 2.1.0+ ​

  • 類型: boolean
  • 預設值: false
  • 可用 providers: 'v8' | 'istanbul'
  • CLI: --coverage.excludeAfterRemap, --coverage.excludeAfterRemap=false

在 coverage 重新映射到原始來源檔案後再次套用排除規則。 當你的來源檔案經過轉譯而且可能包含非來源檔案的 source map 時,此選項很有用。

當你在報告中看到即使與你的 coverage.exclude 模式匹配的檔案仍然出現時,請使用此選項。

coverage.skipFull ​

  • 類型: boolean
  • 預設值: false
  • 適用於提供者: 'v8' | 'istanbul'
  • CLI: --coverage.skipFull, --coverage.skipFull=false

不顯示具有 100% 語句、分支和函數覆蓋率的檔案。

coverage.thresholds ​

覆蓋率閾值選項。

coverage.thresholds.lines ​
  • 類型: number
  • 適用於提供者: 'v8' | 'istanbul'
  • CLI: --coverage.thresholds.lines=<number>

程式碼行的全域閾值: 有關更多資訊,請參閱 istanbul 文件。

coverage.thresholds.functions ​
  • 類型: number
  • 適用於提供者: 'v8' | 'istanbul'
  • CLI: --coverage.thresholds.functions=<number>

函數的全域閾值: 有關更多資訊,請參閱 istanbul 文件。

coverage.thresholds.branches ​
  • 類型: number
  • 適用於提供者: 'v8' | 'istanbul'
  • CLI: --coverage.thresholds.branches=<number>

分支的全域閾值: 有關更多資訊,請參閱 istanbul 文件。

coverage.thresholds.statements ​
  • 類型: number
  • 適用於提供者: 'v8' | 'istanbul'
  • CLI: --coverage.thresholds.statements=<number>

語句的全域閾值: 有關更多資訊,請參閱 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=<boolean>

當目前覆蓋率高於設定的閾值時,將設定檔中的所有閾值 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?: number functions?: number branches?: number lines?: number }
  • 預設值: undefined
  • 適用於提供者: 'v8' | 'istanbul'

設定符合 Glob 模式的檔案的閾值。

注意

Vitest 會將所有檔案(包括那些被 glob 模式覆蓋的檔案)都計入全域覆蓋率閾值。這與 Jest 的行為不同。

ts
{
  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.thresholds[glob-pattern].100 2.1.0+ ​
  • 類型: boolean
  • 預設: false
  • 適用於 providers: 'v8' | 'istanbul'

為符合 glob 模式的檔案設置閾值為 100。

ts
{
  coverage: {
    thresholds: {
      // 所有檔案的閾值
      functions: 95,
      branches: 70,

      // 符合 glob 模式的檔案的閾值
      'src/utils/**.ts': { 100: true },
      '**/math.ts': { 100: true }
    }
  }
}

coverage.ignoreEmptyLines ​

  • 類型: boolean
  • 預設值: true (v1 中為 false)
  • 適用於提供者: 'v8'
  • CLI: --coverage.ignoreEmptyLines=<boolean>

忽略空行、註解和其他非執行階段代碼,例如 TypeScript 類型。

僅當使用的編譯器從轉換後的程式碼中移除註解和其他非執行階段代碼時,此選項才有效。 預設情況下,Vite 使用 ESBuild,它會從 .ts、.tsx 和 .jsx 檔案中移除註解和 Typescript 類型。

如果您也想將 ESBuild 應用於其他檔案,請在 esbuild 選項 中定義它們:

ts
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 ​

  • 類型:
ts
{
  statements?: [number, number],
  functions?: [number, number],
  branches?: [number, number],
  lines?: [number, number]
}
  • 預設值:
ts
{
  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 ​

  • 類型: number
  • 預設值: 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* ​

  • 類型 string | RegExp
  • CLI: -t <pattern>, --testNamePattern=<pattern>, --test-name-pattern=<pattern>

執行名稱完全符合指定模式的測試。 如果此屬性與 OnlyRunThis 一起使用,則測試名稱中不包含 OnlyRunThis 一詞的測試將會被跳過。

js
import { expect, test } from 'vitest';

// 執行
test('OnlyRunThis', () => {
  expect(true).toBe(true);
});

// 跳過
test('doNotRun', () => {
  expect(true).toBe(true);
});

open* ​

  • 類型: boolean
  • 預設值: !process.env.CI
  • CLI: --open, --open=false

開啟 Vitest UI(開發中)。

api ​

  • 類型: boolean | number
  • 預設值: false
  • CLI: --api, --api.port, --api.host, --api.strictPort

監聽指定端口並提供 API。設定為 true 時,預設端口為 51204。

browser ​

  • 類型: { enabled?, name?, provider?, headless?, api? }
  • 預設值: { enabled: false, headless: process.env.CI, api: 63315 }
  • CLI: --browser, --browser=<name>, --browser.name=chrome --browser.headless

在瀏覽器中執行 Vitest 測試。預設情況下,我們使用 WebdriverIO 來執行測試,但可以使用 browser.provider 選項進行配置。

NOTE

請參閱 指南頁面 以了解更多關於在真實瀏覽器中進行測試的相關資訊。

WARNING

這是一個實驗性功能。重大變更可能不會遵循 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
  • custom: 將傳遞給供應商的任何字串

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.testerHtmlPath ​

  • 類型: string
  • 預設值: @vitest/browser/tester.html
  • 版本: 自 Vitest 2.1.4

HTML 進入點的路徑。可以是專案根目錄的相對路徑。此檔案將透過 transformIndexHtml 鉤子進行處理。

browser.api ​

  • 類型: number | { port?, strictPort?, host? }
  • 預設值: 63315
  • CLI: --browser.api=63315、--browser.api.port=1234, --browser.api.host=example.com

設定在瀏覽器中提供程式碼的 Vite 伺服器選項。不影響 test.api 選項。預設情況下,Vitest 分配埠號 63315 以避免與開發伺服器衝突,允許您平行執行兩者。

browser.provider ​

  • 類型: 'webdriverio' | 'playwright' | 'preview' | string
  • 預設值: 'preview'
  • CLI: --browser.provider=playwright

用於執行瀏覽器測試的提供者路徑。Vitest 提供三個提供者:preview (預設)、webdriverio 和 playwright。自訂提供者應使用 default 匯出,並具有以下形狀:

ts
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>;
}

WARNING

這是針對函式庫作者的高級 API。如果您只需要在瀏覽器中執行測試,請使用 browser 選項。

browser.providerOptions ​

  • 類型: BrowserProviderOptions

在呼叫 provider.initialize 時將傳遞給供應商的選項。

ts
export default defineConfig({
  test: {
    browser: {
      providerOptions: {
        launch: {
          devtools: true,
        },
      },
    },
  },
});

TIP

為了在使用內建供應商時獲得更好的類型安全性,您可以將以下類型之一(對於您正在使用的供應商)新增到 tsconfig 的 compilerOptions.types 欄位:

json
{
  "compilerOptions": {
    "types": [
      "@vitest/browser/providers/webdriverio",
      "@vitest/browser/providers/playwright"
    ]
  }
}

browser.ui ​

  • 類型: boolean
  • 預設值: !isCI
  • CLI: --browser.ui=false

是否應將 Vitest UI 注入頁面。預設情況下,在開發期間注入 UI iframe。

browser.viewport ​

  • 類型: { width, height }
  • 預設值: 414x896

預設 iframe 的視窗。

browser.locators ​

內建 瀏覽器定位器 的選項。

browser.locators.testIdAttribute ​
  • 類型: string
  • 預設值: data-testid

用於查找具有 getByTestId 定位器的元素的屬性。

browser.screenshotDirectory ​

  • 類型: string
  • 預設值: 測試檔案目錄中的 __snapshots__

相對於 root 的快照目錄路徑。

browser.screenshotFailures ​

  • 類型: boolean
  • 預設值: !browser.ui

測試失敗時 Vitest 是否應截圖。

browser.orchestratorScripts ​

  • 類型: BrowserScript[]
  • 預設值: []

應在測試 iframe 啟動之前注入到 orchestrator HTML 中的自訂腳本。此 HTML 文件僅設定 iframe,實際上不匯入您的程式碼。

指令碼 src 和 content 將由 Vite 外掛程式處理。指令碼應以以下結構提供:

ts
export interface BrowserScript {
  /**
   * 如果提供了 "content" 且類型為 "module",這將是它的識別碼。
   *
   * 如果您正在使用 TypeScript,您可以在此處新增 `.ts` 副檔名,例如。
   * @default `injected-${index}.js`
   */
  id?: string;
  /**
   * 要注入的 JavaScript 內容。如果類型為 "module",則此字串由 Vite 外掛程式處理。
   *
   * 您可以使用 `id` 來提示 Vite 關於檔案副檔名。
   */
  content?: string;
  /**
   * 指令碼的路徑。此值由 Vite 解析,因此它可以是 node 模組或檔案路徑。
   */
  src?: string;
  /**
   * 指令碼是否應非同步載入。
   */
  async?: boolean;
  /**
   * 指令碼類型。
   * @default 'module'
   */
  type?: string;
}

browser.testerScripts ​

  • 類型: BrowserScript[]
  • 預設值: []

在啟動測試環境之前,應注入到測試器 HTML 中的自訂指令碼。這對於注入 Vitest 瀏覽器實現所需的 polyfill 很有用。建議在幾乎所有情況下都使用 setupFiles 而不是這個選項。

指令碼 src 和 content 將由 Vite 外掛程式處理。

browser.commands ​

  • 類型: Record<string, BrowserCommand>
  • 預設值: { readFile, writeFile, ... }

可以在瀏覽器測試期間從 @vitest/browser/commands 匯入的自訂命令。

clearMocks ​

  • 類型: boolean
  • 預設值: false

將在每個測試之前調用 .mockClear()。這將清除模擬的歷史記錄,但不會將其執行重設為預設執行。

mockReset ​

  • 類型: boolean
  • 預設值: false

將在每個測試之前調用 .mockReset()。這將清除模擬的歷史記錄並將其執行重設為空函數(將傳回 undefined)。

restoreMocks ​

  • 類型: boolean
  • 預設值: false

將在每個測試之前調用 .mockRestore()。這將清除模擬的歷史記錄並將其執行重設為原始執行。

unstubEnvs ​

  • 類型: boolean
  • 預設值: false

將在每個測試之前調用 vi.unstubAllEnvs。

unstubGlobals ​

  • 類型: boolean
  • 預設值: false

將在每個測試之前調用 vi.unstubAllGlobals。

testTransformMode ​

  • 類型: { 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。

TIP

請注意,此物件上的 plugins 欄位將被忽略。

如果您需要透過 pretty-format 外掛程式擴展快照序列化器,請使用 expect.addSnapshotSerializer API 或這個 snapshotSerializers 選項。

snapshotSerializers* ​

  • 類型: string[]
  • 預設值: []

快照序列化器模組的路徑清單,用於快照測試。如果您想新增自訂快照序列化器,這個選項很有用。有關更多資訊,請參閱 自訂序列化器 章節。

resolveSnapshotPath* ​

  • 類型: (testPath: string, snapExtension: string) => string
  • 預設: 將快照檔案儲存在 __snapshots__ 目錄中

覆蓋預設快照路徑。例如,將快照儲存在測試檔案旁邊:

ts
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 樣式。

TIP

要處理所有 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 處理,則會遵循 css.modules.generateScopedName 方法(如果有的話)。預設情況下,檔案名稱將產生為 _${name}_${hash},其中雜湊值包括檔案名稱和檔案內容。
  • non-scoped: 類別名稱將不會被雜湊。

WARNING

預設情況下,Vitest 會匯出一個代理,繞過 CSS 模組處理。如果您依賴於類別上的 CSS 屬性,則必須使用 include 選項啟用 CSS 處理程序。

maxConcurrency ​

  • 類型: number
  • 預設值: 5
  • CLI: --max-concurrency=10, --maxConcurrency=10

允許同時執行的標記為 test.concurrent 的測試數量。

超過此限制的測試將會排隊,等待有可用插槽時執行。

cache* ​

  • 類型: false
  • CLI: --no-cache, --cache=false

如果您想停用快取功能,請使用此選項。目前 Vitest 會儲存測試結果的快取,以便優先執行耗時較長或失敗的測試。

快取目錄由 Vite 的 cacheDir 選項控制:

ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  cacheDir: 'custom-folder/.vitest',
});

您可以使用 process.env.VITEST 將目錄限制僅用於 Vitest:

ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  cacheDir: process.env.VITEST ? 'custom-folder/.vitest' : undefined,
});

sequence ​

  • 類型: { sequencer?, shuffle?, seed?, hooks?, setupFiles? }

用於指定測試排序方式的選項。

您可以透過 CLI 使用點表示法來指定序列選項:

sh
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 ​

  • 類型: boolean
  • 預設值: false
  • CLI: --sequence.shuffle.files, --sequence.shuffle.files=false

是否隨機化檔案。請注意,如果啟用此選項,執行時間較長的測試將不會更早開始。

sequence.shuffle.tests ​

  • 類型: boolean
  • 預設值: false
  • CLI: --sequence.shuffle.tests, --sequence.shuffle.tests=false

是否隨機化測試。

sequence.concurrent ​

  • 類型: boolean
  • 預設值: false
  • CLI: --sequence.concurrent, --sequence.concurrent=false

如果您希望測試並行執行,可以使用此選項或 CLI 參數 --sequence.concurrent 來啟用它。

sequence.seed* ​

  • 類型: number
  • 預設值: Date.now()
  • CLI: --sequence.seed=1000

設定隨機化種子,用於測試以隨機順序執行時。

sequence.hooks ​

  • 類型: 'stack' | 'list' | 'parallel'
  • 預設值: 'parallel'
  • CLI: --sequence.hooks=<value>

變更 Hook 的執行順序。

  • stack 將以相反順序執行 "after" Hook,而 "before" Hook 則按照其定義順序執行
  • list 將按照其定義順序排序所有 Hook
  • parallel 將並行地在單一群組中執行 Hook (父套件中的 Hook 仍會在目前套件的 Hook 之前執行)

TIP

此選項不影響 onTestFinished。它始終以相反的順序被呼叫。

sequence.setupFiles ​

  • 類型: 'list' | 'parallel'
  • 預設值: 'parallel'
  • CLI: --sequence.setupFiles=<value>

變更設定檔執行的順序。

  • list 將按照它們被定義的順序執行設定檔
  • parallel 將並行執行設定檔

typecheck ​

用於配置 類型檢查 測試環境的選項。

typecheck.enabled ​

  • 類型: boolean
  • 預設值: false
  • CLI: --typecheck, --typecheck.enabled

在執行常規測試時啟用類型檢查。

typecheck.only ​

  • 類型: boolean
  • 預設值: false
  • CLI: --typecheck.only

啟用類型檢查後,僅執行類型檢查的測試。使用 CLI 時,此選項將自動啟用類型檢查。

typecheck.checker ​

  • 類型: 'tsc' | 'vue-tsc' | string
  • 預設值: tsc

指定用於類型檢查的工具。Vitest 將產生一個帶有特定參數的進程,以便於解析,具體取決於類型。Checker 應實作與 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 ​

  • 類型: string
  • 預設值: 嘗試尋找最接近的 tsconfig.json

自訂 tsconfig 的路徑,相對於專案根目錄。

slowTestThreshold* ​

  • 類型: number
  • 預設值: 300
  • CLI: --slow-test-threshold=<number>, --slowTestThreshold=<number>

測試或套件被視為慢速並在結果中報告的閾值毫秒數。

chaiConfig ​

  • 類型: { includeStack?, showDiff?, truncateThreshold? }
  • 預設值: { includeStack: false, showDiff: true, truncateThreshold: 40 }

等同於 Chai config。

chaiConfig.includeStack ​

  • 類型: boolean
  • 預設值: false

控制是否在 assertion 錯誤訊息中包含堆疊追蹤。預設值 false 會抑制錯誤訊息中的堆疊追蹤。

chaiConfig.showDiff ​

  • 類型: boolean
  • 預設值: true

影響是否應在拋出的 AssertionErrors 中包含 showDiff 標記。false 將始終為 false;當斷言已請求顯示差異時,true 才會為 true。

chaiConfig.truncateThreshold ​

  • 類型: number
  • 預設值: 40

設定斷言錯誤中實際值和預期值的長度閾值。如果超過此閾值,例如對於大型資料結構,則該值將被替換為類似 [ Array(3) ] 或 { Object (prop1, prop2) } 的內容。如果您想完全停用截斷功能,請將其設定為 0。

此配置選項會影響截斷 test.each 標題和斷言錯誤訊息中的值。

bail ​

  • 類型: number
  • 預設值: 0
  • CLI: --bail=<value>

當指定數量的測試失敗時,停止測試執行。

預設情況下,即使部分測試失敗,Vitest 仍會執行所有測試案例。這可能不適用於僅對 100% 成功的建置感興趣,並希望在發生測試失敗時儘早停止測試執行的 CI 建置。bail 選項可用於透過防止 CI 在發生失敗時執行更多測試,來加速 CI 執行。

retry ​

  • 類型: number
  • 預設值: 0
  • CLI: --retry=<value>

若測試失敗,則會重試指定次數。

onConsoleLog* ​

  • 類型: (log: string, type: 'stdout' | 'stderr') => boolean | void

用於自訂測試中 console.log 的處理方式。如果您返回 false,Vitest 將不會將日誌列印到控制台。

可用於過濾掉來自第三方函式庫的日誌。

ts
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* ​

  • 類型: (error: Error, frame: ParsedStack) => boolean | void

在處理錯誤時,將篩選函式應用於每個堆疊追蹤的每個影格。第一個參數 error 是一個物件,其屬性與標準 Error 相同,但它不是實際的實例。

可用於過濾掉來自第三方函式庫的堆疊追蹤影格。

ts
import type { ParsedStack } from 'vitest';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    onStackTrace(error: Error, { file }: ParsedStack): boolean | void {
      // 如果我們遇到 ReferenceError,則顯示整個堆疊。
      if (error.name === 'ReferenceError') return;

      // 拒絕來自第三方函式庫的所有影格。
      if (file.includes('node_modules')) return false;
    },
  },
});

diff ​

  • 類型: string
  • CLI: --diff=<value>

指定用於產生差異介面的設定檔路徑。如果您想自訂差異顯示,這很有用。

ts
import type { DiffOptions } from 'vitest';
import c from 'tinyrainbow';

export default {
  aIndicator: c.bold('--'),
  bIndicator: c.bold('++'),
  omitAnnotationLines: true,
} satisfies DiffOptions;
ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    diff: './vitest.diff.ts',
  },
});

diff.truncateThreshold ​

  • 類型: number
  • 預設值: 0

設定差異結果顯示的最大長度。超過此閾值的差異將會被截斷。截斷功能預設為停用 (值為 0)。

diff.truncateAnnotation ​

  • 類型: string
  • 預設值: '... Diff result is truncated'

如果差異結果被截斷,則在差異結果末尾輸出的註解。

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 ​

  • 類型: number
  • 預設值: 10_000

呼叫 vi.runAllTimers() 時將執行的最大計時器數量。

fakeTimers.shouldAdvanceTime ​

  • 類型: boolean
  • 預設值: false

告知 @sinonjs/fake-timers 基於真實系統時間偏移自動遞增模擬時間 (例如,對於真實系統時間的每次 20 毫秒變化,模擬時間將遞增 20 毫秒)。

fakeTimers.advanceTimeDelta ​

  • 類型: number
  • 預設值: 20

僅在使用 shouldAdvanceTime: true 時相關。每次真實系統時間變化 advanceTimeDelta 毫秒時,將模擬時間遞增 advanceTimeDelta 毫秒。

fakeTimers.shouldClearNativeTimers ​

  • 類型: boolean
  • 預設: true

告知 fake timers 透過委派給各自的處理程式來清除「原生」(也就是非假) 定時器。停用時,如果在啟動 fake timers 工作階段之前存在定時器,可能會導致潛在的非預期行為。

workspace* ​

  • 類型: string
  • CLI: --workspace=./file.js
  • 預設值: vitest.{workspace,projects}.{js,ts,json} 靠近設定檔或根目錄

相對於 root 的 工作區 設定檔路徑。

isolate ​

  • 類型: boolean
  • 預設值: true
  • CLI: --no-isolate, --isolate=false

在隔離環境中執行測試。此選項對 vmThreads 和 vmForks 池沒有影響。

若您的程式碼不依賴副作用 (對於具有 node 環境的專案通常是如此),停用此選項可能會 提高效能。

TIP

您可以使用 poolOptions 屬性為特定池停用隔離。

includeTaskLocation ​

  • 類型: boolean
  • 預設值: false

當 Vitest API 在 reporters 中接收任務時,是否應包含 location 屬性。若測試數量龐大,可能會導致效能略微下降。

location 屬性具有與原始檔案中 test 或 describe 位置對應的 column 和 line 值。

如果您沒有明確停用此選項,且您正在透過以下方式執行 Vitest,則此選項將自動啟用:

  • Vitest UI
  • 或者使用 瀏覽器模式 而非 headless 模式
  • 或者使用 HTML 報告器

TIP

如果您不使用依賴於此的自訂程式碼,則此選項無效。

snapshotEnvironment ​

  • 類型: string

指定自訂快照環境實現的路徑。如果您在不支援 Node.js API 的環境中執行測試,這很有用。此選項對瀏覽器執行器沒有任何影響。

此物件應具有 SnapshotEnvironment 的結構,並用於解析和讀取/寫入快照檔案:

ts
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。

WARNING

此為進階選項,僅應在您無法存取預設 Node.js API 的情況下使用。

如果您只需要配置快照功能,請使用 snapshotFormat 或 resolveSnapshotPath 的選項。

env ​

  • 類型: Partial<NodeJS.ProcessEnv>

測試期間可在 process.env 和 import.meta.env 中使用的環境變數。這些變數在主程式中不可用(例如在 globalSetup 中)。

expect ​

  • 類型: ExpectOptions

expect.requireAssertions ​

  • 類型: boolean
  • 預設: false

與在每個測試開始時呼叫 expect.hasAssertions() 相同。這可確保沒有測試會意外通過。

TIP

這僅適用於 Vitest 的 expect。如果您使用 assert 或 .should 斷言,它們將不會計入,並且您的測試將因缺少 expect 斷言而失敗。

您可透過呼叫 vi.setConfig({ expect: { requireAssertions: false } }) 來變更此值。此組態將應用於之後的所有 expect 呼叫,直到手動呼叫 vi.resetConfig。

expect.poll ​

expect.poll 的全域組態選項。這些選項與您傳遞給 expect.poll(condition, options) 的選項相同。

expect.poll.interval ​
  • 類型: number
  • 預設: 50

以毫秒為單位的輪詢間隔

expect.poll.timeout ​
  • 類型: number
  • 預設: 1000

以毫秒為單位的輪詢超時時間

printConsoleTrace ​

  • 類型: boolean
  • 預設: false

呼叫任何 console 方法時一律列印控制台追蹤。這對於偵錯非常有用。

Pager
上一頁管理 Vitest 配置文件

以 MIT 授權條款 發布。

版權所有 (c) 2021-Present Vitest Team

https://v2.vitest.dev/config/

以 MIT 授權條款 發布。

版權所有 (c) 2021-Present Vitest Team