在 Next.js 中設定 Vitest

Vite 和 React Testing Library 經常一起用於單元測試 (Unit Testing)。本指南將展示如何在 Next.js 中設定 Vitest 並撰寫第一個測試。

小知識:由於 async 伺服器元件 (Server Components) 是 React 生態系統中的新功能,Vitest 目前不支援它們。雖然您仍然可以為同步的伺服器和客戶端元件執行單元測試,但我們建議對 async 元件使用端到端測試 (E2E tests)

快速開始

您可以使用 create-next-app 搭配 Next.js 的 with-vitest 範例快速開始:

終端機
npx create-next-app@latest --example with-vitest with-vitest-app

手動設定

要手動設定 Vitest,請將 vitest 和以下套件安裝為開發依賴項:

終端機
npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react
# 或
yarn add -D vitest @vitejs/plugin-react jsdom @testing-library/react
# 或
pnpm install -D vitest @vitejs/plugin-react jsdom @testing-library/react
# 或
bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react

在專案根目錄建立一個 vitest.config.ts|js 檔案,並加入以下設定:

import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
  },
})

有關設定 Vitest 的更多資訊,請參考 Vitest 設定文件

接著,在 package.json 中加入 test 指令:

package.json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test": "vitest"
  }
}

當您執行 npm run test 時,Vitest 預設會監聽專案中的變更。

建立第一個 Vitest 單元測試

建立一個測試來檢查 <Page /> 元件是否成功渲染標題,以確認一切正常運作:

import Link from 'next/link'

export default function Page() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}

**小知識:**上面的範例使用了常見的 __tests__ 慣例,但測試檔案也可以放在 app 路由中與其他檔案共存。

執行測試

接著,執行以下指令來執行測試:

終端機
npm run test
# 或
yarn test
# 或
pnpm test
# 或
bun test

其他資源

您可能會覺得這些資源有幫助:

On this page