GitHub Actions CI: build, test, artifact upload
🎯 Mục tiêu: Tạo workflow GitHub Actions tự động build Node.js app, chạy unit test, upload artifact ZIP mỗi khi push lên nhánh main.
🧰 Công cụ / nền tảng: GitHub (tài khoản free), Git, Node.js 20, VS Code.
📦 Chuẩn bị: Tạo repo GitHub mới (public hoặc private). Cài Node.js 20 trên máy local. Có gh CLI (tùy chọn).
▶️ Các bước:
# 1. Khởi tạo dự án Node.js tối giản
mkdir ci-demo && cd ci-demo
git init
npm init -y
npm install --save-dev jest
# 2. Tạo file ứng dụng và test
cat > src/math.js << 'EOF'
function add(a, b) { return a + b; }
module.exports = { add };
EOF
cat > src/math.test.js << 'EOF'
const { add } = require('./math');
test('add 2+3 = 5', () => expect(add(2, 3)).toBe(5));
EOF
# Cập nhật package.json test script
npm pkg set scripts.test="jest"
npm pkg set scripts.build="echo 'Build OK' && mkdir -p dist && cp src/*.js dist/"
# 3. Chạy test cục bộ để xác nhận
npm test
# 4. Tạo GitHub Actions workflow
mkdir -p .github/workflows
cat > .github/workflows/ci.yml << 'EOF'
name: CI Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build-and-test:
runs-on: ubuntu-latest
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run unit tests
run: npm test -- --ci --coverage
- name: Build artifact
run: npm run build
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: build-${{ github.sha }}
path: dist/
retention-days: 7
EOF
# 5. Commit và push
git add .
git commit -m "feat: add ci pipeline with build, test, artifact upload"
git remote add origin https://github.com/<username>/ci-demo.git
git push -u origin main
# 6. Theo dõi workflow (yêu cầu gh CLI)
gh run watch
🖥️ Đối chiếu GUI (Portal): Vào GitHub → tab Actions → click workflow run → xem log từng step; tab Artifacts để download file build.
✅ Kết quả mong đợi: Workflow hiển thị dấu tích xanh; log test in PASS src/math.test.js; artifact build-<sha> xuất hiện trong tab Artifacts có thể download.
🧹 Cleanup: Artifact tự xóa sau 7 ngày. Xóa repo nếu không cần: gh repo delete ci-demo --yes.