工程部署
Quality AssuranceVitest
測試 (Testing)
穩健的應用程式建立在可靠的測試之上。Nuxt 提供了官方的測試工具 @nuxt/test-utils,讓測試變得簡單而強大。
為什麼要測試?
隨著專案規模擴大,手動測試每一個功能變得不可能。自動化測試可以:
- 防止回歸錯誤 (Regressions)
- 作為活的文件 (Documentation)
- 更有信心地重構程式碼
- 提早發現潛在 Bug
環境建置
我們使用 Vitest 作為測試執行器,並搭配 @nuxt/test-utils 來存取 Nuxt 的運行環境 (Runtime Environment)。
Terminal
pnpm add -D vitest @nuxt/test-utils happy-dom @vue/test-utils playwright-core接著,在專案根目錄建立 vitest.config.ts:
vitest.config.ts
import { defineVitestConfig } from '@nuxt/test-utils/config'
export default defineVitestConfig({
// 任何額外的 Vitest 設定
test: {
environment: 'nuxt', // 模擬 Nuxt 環境
// 可以在這裡設定 coverage, reporters 等
}
}) 單元測試 (Unit Testing)
單元測試主要針對獨立的邏輯進行驗證,例如 utils 或 composables。
tests/utils.test.ts
tests/utils.test.ts
import { describe, it, expect } from 'vitest'
import { formatCurrency } from '../app/utils/format'
describe('Utils: formatCurrency', () => {
it('should format number to TWD currency', () => {
const result = formatCurrency(1000)
expect(result).toBe('NT$1,000.00') // 假設這是預期輸出
})
it('should handle zero', () => {
expect(formatCurrency(0)).toBe('NT$0.00')
})
}) 得益於 @nuxt/test-utils,你甚至可以在測試中直接使用 Auto-imports:
tests/hello.test.ts
tests/hello.test.ts
import { describe, it, expect } from 'vitest'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
// 模擬 useRuntimeConfig
mockNuxtImport('useRuntimeConfig', () => {
return () => ({
public: { apiBase: 'https://test-api.com' }
})
})
describe('Composables', () => {
it('can access runtime config', () => {
const config = useRuntimeConfig()
expect(config.public.apiBase).toBe('https://test-api.com')
})
}) 端對端測試 (E2E)
E2E 測試會啟動真實的瀏覽器,模擬使用者操作。我們先確保安裝了 Playwright 瀏覽器:
Terminal
npx playwright install撰寫一個簡單的瀏覽器測試:
tests/e2e/home.test.ts
import { describe, it, expect } from 'vitest'
import { setup, createPage } from '@nuxt/test-utils/e2e'
describe('Home Page', async () => {
await setup({
// 會自動啟動 Nuxt server
})
it('should have correct title', async () => {
const page = await createPage('/')
const text = await page.textContent('h1')
expect(text).toContain('Nuxt 4 Tutorial')
})
})E2E 測試執行速度較慢,但能提供最高的信心保證。建議在 CI/CD 流程中執行。