我們來設計一套完整流程:**每次執行 GitHub Action 自動測試時,啟動一個乾淨的 PostgreSQL DB 並填入測試資料,再讓後端進行自動測試。** 我會幫你拆成以下四步來做分享 & Demo: --- ## ✅ 目標:用 GitHub Actions + Docker 自動建立測試資料庫並執行測試 --- ### 🧱 架構概覽 ```txt GitHub Action │ ├─ 啟動 service: postgres (乾淨容器) │ ├─ 安裝 Node.js / yarn │ ├─ 等待 DB 就緒 │ ├─ 執行 migration & seed(建表 + 假資料) │ └─ 執行 Jest / Supertest 自動測試 ``` --- ### 🧩 專案需求 - Node.js + Express(後端) - TypeORM / Prisma / Sequelize 皆可(這邊以 TypeORM 為例) - PostgreSQL(用 GitHub Action 的 container service 啟動) - 假資料可用 `seed.ts` 或 `fixtures` --- ## 🔧 GitHub Actions 設定(`test.yml`) ```yaml name: Run backend tests with DB on: push: branches: [main] pull_request: branches: [main] jobs: test: runs-on: ubuntu-latest services: postgres: image: postgres:15 ports: - 5432:5432 env: POSTGRES_DB: testdb POSTGRES_USER: testuser POSTGRES_PASSWORD: testpass options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 env: DB_HOST: localhost DB_PORT: 5432 DB_NAME: testdb DB_USER: testuser DB_PASS: testpass steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' - name: Install dependencies run: yarn install - name: Wait for DB to be ready run: | until pg_isready -h localhost -p 5432 -U testuser; do echo "Waiting for postgres..." sleep 3 done - name: Run migrations run: yarn typeorm migration:run - name: Seed database run: yarn seed:test - name: Run tests run: yarn test ``` --- ## 🧪 seed 檔案實作(假設用 TypeORM) ### `src/seeds/testSeed.ts` ```ts import { AppDataSource } from "../data-source"; import { User } from "../entity/User"; (async () => { await AppDataSource.initialize(); const userRepo = AppDataSource.getRepository(User); const fakeUser = userRepo.create({ name: "Henry", email: "henry@test.com" }); await userRepo.save(fakeUser); console.log("✅ Seed complete"); process.exit(0); })(); ``` ### 加到 `package.json` ```json "scripts": { "seed:test": "ts-node src/seeds/testSeed.ts" } ``` --- ## ✅ Bonus:測試成功畫面 測試成功後,GitHub Action workflow log 會顯示: ```bash ✅ Seed complete PASS tests/user.test.ts ✔ returns user list (123 ms) ``` --- ## 🧑🏫 分享 Demo 引導流程建議 1. 展示 `.github/workflows/test.yml` 架構 2. 解釋 `services.postgres` 是 GitHub Action 提供的 container service 3. 開一個 PR ➜ 自動啟動 DB ➜ seed ➜ 跑測試 4. 故意改一筆 seed ➜ 測試壞掉 ➜ demo test failure 5. 分享「本地也可以用 docker-compose 跑類似環境測試」 --- ## 📎 補充:本地端測試用 `docker-compose` 本地測試: ```yaml services: postgres: image: postgres:15 ports: - "5432:5432" environment: POSTGRES_DB: testdb POSTGRES_USER: testuser POSTGRES_PASSWORD: testpass ``` ---
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up