Q30 of 38 · CI/CD & DevOps
How do you write a GitHub Actions workflow for running automated tests on every pull request?
Short answer
Short answer: Create a .github/workflows/test.yml that triggers on pull_request, checks out the code, caches dependencies, runs your test command, and uploads artifacts on failure. Wire it to branch protection so a failing check blocks the merge button.
Detail
The core pattern: trigger on pull_request, use actions/checkout and actions/cache (or the built-in cache in actions/setup-node), run your test command, then upload the report directory with if: failure().
For secrets: store them in GitHub repository settings (Settings → Secrets and variables → Actions) and reference them as environment variables. Never hard-code credentials in workflow files.
Branch protection rules enforce the requirement: in Settings → Branches, require the test workflow status check to pass before any PR can merge. This makes the gate mandatory regardless of who opens the PR.
// EXAMPLE
.github/workflows/test.yml
name: Tests
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm test
- uses: actions/upload-artifact@v4
if: failure()
with:
name: test-results
path: test-results/