跳至內容

測試環境

Vitest 提供 environment 選項,可在特定環境中執行程式碼。你可以使用 environmentOptions 選項修改環境行為。

預設情況下,你可以使用下列環境

  • node 是預設環境
  • jsdom 模擬瀏覽器環境,提供瀏覽器 API,使用 jsdom 套件
  • happy-dom 模擬瀏覽器環境,提供瀏覽器 API,且被認為比 jsdom 更快,但缺少一些 API,使用 happy-dom 套件
  • edge-runtime 模擬 Vercel 的 edge-runtime,使用 @edge-runtime/vm 套件

特定檔案的環境

在設定 config 中的 environment 選項時,它會套用於專案中的所有測試檔案。若要進行更精細的控制,可以使用控制註解來指定特定檔案的環境。控制註解是從 @vitest-environment 開始並後接環境名稱的註解

ts
// @vitest-environment jsdom

import { ,  } from 'vitest'

('test', () => {
  (typeof )..('undefined')
})

或者,您也可以設定 environmentMatchGlobs 選項,根據 glob 模式指定環境。

自訂環境

從 0.23.0 開始,您可以建立自己的套件來擴充 Vitest 環境。為此,請建立名稱為 vitest-environment-${name} 的套件,或指定路徑至有效的 JS/TS 檔案(自 0.34.0 起支援)。該套件應匯出具有 Environment 形狀的物件

ts
import type { Environment } from 'vitest'

export default <Environment>{
  : 'custom',
  : 'ssr',
  // optional - only if you support "experimental-vm" pool
  async () {
    const  = await import('node:vm')
    const  = .()
    return {
      () {
        return 
      },
      () {
        // called after all tests with this env have been run
      }
    }
  },
  () {
    // custom setup
    return {
      () {
        // called after all tests with this env have been run
      }
    }
  }
}

警告

自 0.34.0 起,Vitest 要求環境物件具有 transformMode 選項。它應等於 ssrweb。此值決定外掛程式將如何轉換原始碼。如果設定為 ssr,外掛程式掛鉤在轉換或解析檔案時會收到 ssr: true。否則,ssr 會設定為 false

您也可以透過 vitest/environments 項目存取預設的 Vitest 環境

ts
import { ,  } from 'vitest/environments'

.() // { jsdom, happy-dom, node, edge-runtime }

Vitest 也提供 populateGlobal 實用程式函式,可用於將屬性從物件移至全域命名空間

ts
interface PopulateOptions {
  // should non-class functions be bind to the global namespace
  bindFunctions?: boolean
}

interface PopulateResult {
  // a list of all keys that were copied, even if value doesn't exist on original object
  keys: Set<string>
  // a map of original object that might have been overridden with keys
  // you can return these values inside `teardown` function
  originals: Map<string | symbol, any>
}

export function populateGlobal(global: any, original: any, options: PopulateOptions): PopulateResult