Vue Node.js 測試策略 - paulip114/blog GitHub Wiki
- 🎨 前端:Vue + TypeScript + Quasar
- 🛠️ 後端:Node.js Express
🧪 整體測試策略架構
使用者 (E2E Test)
↓
┌───────────────┐
│ 前端應用(Vue)│ ← Functional, Unit, Component
└───────────────┘
↓
API 請求(Integration Test)
↓
┌───────────────┐
│ 後端 API (Node)│ ← Unit, Integration
└───────────────┘
↓
資料庫、外部服務
🎨 前端(Vue + TS + Quasar)
✅ 1. Unit Tests(單元測試)
測試你 Vue component 的 method、computed、store logic(如 Pinia)。
- 工具建議:
Vitest
(更快更現代)或Jest
- 搭配:
@vue/test-utils
安裝 Vitest(單元測試 & component 測試)
npm install -D vitest vue-test-utils jsdom @testing-library/vue @vitejs/plugin-vue
然後在 vite.config.ts
裡加上 Vitest 支援(Quasar CLI 會有類似設定):
test: {
environment: 'jsdom',
globals: true,
setupFiles: './src/test/setup.ts', // optional
}
📁 建議目錄結構:
/src
/components
MyComponent.vue
MyComponent.spec.ts ← 單元測試
📦 範例:
import { mount } from '@vue/test-utils'
import MyComponent from '@/components/MyComponent.vue'
test('should emit event', () => {
const wrapper = mount(MyComponent)
wrapper.find('button').trigger('click')
expect(wrapper.emitted()).toHaveProperty('submit')
})
✅ 2. Component / Snapshot Tests
驗證組件渲染是否正確,可加快對 UI 回歸的追蹤。
✅ 3. End-to-End Test(E2E 測試)
模擬使用者真實操作整個 App(點擊、表單、導覽等)
- 工具:
Playwright
或Cypress
- 可以模擬登入、填表、導航等
Cypress 安裝步驟(前端專案)
🔧 Step 1:安裝 Cypress
npm install -D cypress
🔧 Step 2:初始化 Cypress
npx cypress open
這會打開 Cypress 的 GUI 並自動建立 cypress/
資料夾,包含:
/cypress
/e2e
spec.cy.ts ← 可以改這個來寫自己的測試
/support
/fixtures
🧠 註:如果你使用 TypeScript,可以把檔名用
.cy.ts
或.spec.ts
,它都認得。
🔧 Step 3:新增測試(以登入為例)
// cypress/e2e/login.cy.ts
describe('Login Page', () => {
it('logs in successfully', () => {
cy.visit('http://localhost:9000/login') // Quasar 本地開發網址
cy.get('input[name="email"]').type('[email protected]')
cy.get('input[name="password"]').type('123456')
cy.get('button[type="submit"]').click()
cy.url().should('include', '/dashboard')
})
})
🔧 Step 4:在 Quasar 裡跑起你的前端(如果還沒)
quasar dev
然後開另一個 terminal:
npx cypress open
選你剛剛的 .cy.ts
檔案,就會看到它在 GUI 裡自動跑!
🚀 寫更多測試的好習慣
- 建議每個使用者流程(登入、註冊、建立資料)寫一個
.cy.ts
- 可以共用 login 函式放進
cypress/support/commands.ts
- 如果你有 API Token 流程,可以透過 API 模擬登入來加快速度("programmatic login")
package.json
🧰 加上 script 到 "scripts": {
"test:e2e": "cypress open",
"test:e2e:headless": "cypress run"
}
這樣你用 CLI 跑也很方便:
npm run test:e2e
✅ 現在你已經有:
- Quasar 前端
- Cypress E2E 測試
- 可測登入、表單、按鈕流程
🛠️ 後端(Node.js + Express 或其他框架)
✅ 1. Unit Test
- 測試純函式、controller 邏輯。
- 工具建議:
Vitest
,Jest
,Mocha
安裝 Vitest + Supertest(單元 + API 整合)
npm install -D vitest supertest
撰寫範例:
// test/user.test.ts
import request from 'supertest'
import app from '../src/app'
test('GET /api/user', async () => {
const res = await request(app).get('/api/user/1')
expect(res.statusCode).toBe(200)
})
📦 範例:
import { getUser } from '../controllers/user'
test('should return user by id', async () => {
const req = { params: { id: '123' } }
const res = { json: vi.fn() }
await getUser(req, res)
expect(res.json).toBeCalledWith(expect.objectContaining({ id: '123' }))
})
✅ 2. Integration Test
測試 API 路由 + DB + Service 整合(但不用跑整個前端)
- 工具:
supertest
搭配Jest
/Vitest
- 可搭配測試資料庫(如 SQLite 或 Docker 版 MongoDB)
📦 範例:
import request from 'supertest'
import app from '../app'
test('GET /api/user/123', async () => {
const res = await request(app).get('/api/user/123')
expect(res.statusCode).toBe(200)
expect(res.body.id).toBe('123')
})
mongodb-memory-server
(測試用內存DB)
如果你使用 MongoDB,可以考慮裝 npm install -D mongodb-memory-server
這樣測試時不會污染真實資料庫。
🧪 全流程 End-to-End 測試
若要測試「前端 + API + DB」的整體流程,可以用 Playwright/Cypress:
- 前端點擊登入 → API 驗證 → DB 回傳 → 畫面顯示
- 可以模擬真實部署環境,最好在 CI/CD 上跑
✅ Coverage 工具(代碼覆蓋率)
Vitest 已內建支援,直接加上:
npx vitest --coverage
會顯示:
Statements : 85%
Branches : 78%
Functions : 90%
Lines : 85%
package.json
裡的 scripts:
📜 最後建議加在 "scripts": {
"test": "vitest",
"test:unit": "vitest run",
"test:e2e": "playwright test",
"coverage": "vitest run --coverage"
}
🧰 工具總表
測試類型 | 前端工具 | 後端工具 |
---|---|---|
Unit | Vitest, Jest | Vitest, Jest, Mocha |
Component | @vue/test-utils | N/A |
Integration | Axios + MSW / mock server | Supertest + test DB |
E2E | Cypress / Playwright | 連動 API |
Coverage | c8 , nyc , vitest --coverage |
nyc , c8 |
🚀 加入 CI/CD
建議把這些整合進 GitHub Actions / GitLab CI:
# .github/workflows/test.yml
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: npm ci
- run: npm run test:unit
- run: npm run test:e2e
✅ Bonus:測試優先順序建議(Test Pyramid)
🔼 數量少 / 慢
E2E Tests
Integration Tests
Unit Tests(快速、便宜)
🔽 數量多 / 快