使用 Next.js 設定 Vitest (Setting up Vitest with Next.js)
Vite 和 React 測試函式庫經常搭配使用於單元測試。本指南將示範如何使用 Next.js 設定 Vitest 並撰寫您的第一個測試。(Vite and React Testing Library are frequently used together for Unit Testing. This guide will show you how to setup Vitest with Next.js and write your first tests.)
貼心小提醒:由於
async
伺服器元件在 React 生態系中仍屬新穎,Vitest 目前尚不支援。雖然您仍然可以對同步的伺服器和客戶端元件執行單元測試,但我們建議您對async
元件使用端對端測試 (E2E 測試)。
快速入門
您可以使用 Next.js 的 with-vitest 範例搭配 create-next-app
快速上手。
終端機
npx create-next-app@latest --example with-vitest with-vitest-app
手動設定
若要手動設定 Vitest,請將 vitest
和以下套件安裝為開發依賴項。
終端機
npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
# or
yarn add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
# or
pnpm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
# or
bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
在專案的根目錄中建立一個 vitest.config.ts|js
檔案,並新增以下選項。
vitest.config.ts
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 />
元件是否成功渲染標題,以確認一切正常運作。
pages/index.tsx
import Link from 'next/link'
export default function Page() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}
__tests__/index.test.tsx
import { expect, test } from 'vitest'
import { render, screen } from '@testing-library/react'
import Page from '../pages/index'
test('Page', () => {
render(<Page />)
expect(screen.getByRole('heading', { level: 1, name: 'Home' })).toBeDefined()
})
執行您的測試
然後,執行以下指令來執行您的測試。
終端機
npm run test
# or
yarn test
# or
pnpm test
# or
bun test
其他資源
您可能會發現這些資源很有幫助
這有幫助嗎?