跳至內容

內源測試

Vitest 也提供一種方式,可以在原始碼中執行測試,與實作並列,類似於 Rust 的模組測試

這使得測試與實作共用同一個封閉,並能夠在不匯出的情況下針對私有狀態進行測試。同時,它也為開發帶來更緊密的回饋迴路。

設定

要開始使用,請在原始檔的結尾放置一個 if (import.meta.vitest) 區塊,並在其中撰寫一些測試。例如

ts
// src/index.ts

// the implementation
export function add(...args: number[]) {
  return args.reduce((a, b) => a + b, 0)
}

// in-source test suites
if (import.meta.vitest) {
  const { it, expect } = import.meta.vitest
  it('add', () => {
    expect(add()).toBe(0)
    expect(add(1)).toBe(1)
    expect(add(1, 2, 3)).toBe(6)
  })
}

更新 Vitest 的 includeSource 設定,以擷取 src/ 底下的檔案

ts
// vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'

export default defineConfig({
  test: {
    includeSource: ['src/**/*.{js,ts}'], 
  },
})

然後就可以開始測試了!

bash
$ npx vitest

生產版本

對於製作版本,您需要在設定檔中設定 define 選項,讓套件管理程式執行無用程式碼移除。例如,在 Vite 中

ts
// vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'

export default defineConfig({
  test: {
    includeSource: ['src/**/*.{js,ts}'],
  },
  define: { 
    'import.meta.vitest': 'undefined', 
  }, 
})

其他套件管理程式

unbuild
ts
// build.config.ts
import { defineBuildConfig } from 'unbuild'

export default defineBuildConfig({
  replace: { 
    'import.meta.vitest': 'undefined', 
  }, 
  // other options
})

Learn more: unbuild

Rollup
ts
// rollup.config.js
import replace from '@rollup/plugin-replace'

export default {
  plugins: [
    replace({ 
      'import.meta.vitest': 'undefined', 
    }) 
  ],
  // other options
}

Learn more: Rollup

TypeScript

若要取得 import.meta.vitest 的 TypeScript 支援,請將 vitest/importMeta 新增至您的 tsconfig.json

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

請參閱 test/import-meta 以取得完整範例。

注意事項

此功能可能對下列情況有用

  • 針對小範圍函式或公用程式進行單元測試
  • 原型製作
  • 內嵌斷言

建議對於較複雜的測試(例如元件或 E2E 測試),改用獨立的測試檔案