Overview and What You Will Learn
A testing gate is a pipeline stage that must pass before code moves forward. Fast unit tests run on every commit, integration tests check the service against real dependencies, and a small set of smoke tests verifies each deployment after release. Together they let a team deploy many times a day, because every change is checked automatically before and after it ships.
In this lab you will:
- Shape a test suite with the test pyramid and map each layer to a CI stage.
- Run sharded unit tests and enforce coverage on the merged result.
- Run integration tests against real PostgreSQL and Redis service containers.
- Verify each deployment with smoke tests and roll back on failure.
- Publish readable test results on the pull request.
- Detect, quarantine, and fix flaky tests.
Why This Matters in Production
Without automated gates, a broken payment flow may only be found by QA days later, after more commits have piled on top. With gates, the failure shows on the pull request within minutes of the commit, when the fix is one line and the author still remembers the change.
Gates also protect trust. If the pipeline is slow or randomly red, engineers stop reading it. A payments team at a company like Razorpay or Stripe needs a suite that is fast, deterministic, and blocking, so a green build genuinely means safe to ship.
Common MistakePutting
continue-on-error: trueon the main test job to stop red builds. The pipeline becomes always green, which is worse than no tests because it creates false confidence. Use it only for explicitly quarantined flaky tests you track separately.
Core Principles
The test pyramid keeps feedback fast. Many cheap unit tests sit at the bottom, fewer integration tests in the middle, and a handful of end-to-end checks at the top. Each layer runs at the stage where it gives the most signal for the least time.
Each test type has a job and a gate.
| Test type | Runs when | On failure |
|---|---|---|
| Unit | Every commit and PR | Block the pipeline |
| Integration | Every PR and merge | Block the pipeline |
| Smoke | After each deploy | Roll back |
Unit tests check one piece in isolation. They take milliseconds each, use no network, and should be the bulk of the suite.
Integration tests check the service with real dependencies. They use a real database and cache, so they catch query, migration, and serialization bugs that mocks hide.
Smoke tests check that a deployed service works. They are few and fast, covering the health endpoint and one or two critical user flows. They verify the deployment, not every feature.
Coverage is a floor, not a quality score. A coverage threshold stops regression, but a test with no assertions still counts. Reviews must check that tests assert real behaviour.
TipOn pull requests, run only tests related to changed files with
jest --changedSince=origin/main. Do not enforce a global coverage threshold on that partial run, because it will read low.
Detailed Step-by-Step Practical Lab
This lab builds the testing stages for a Node.js payment-api service. Commands assume Jest.
Milestone 1 - Configure Jest with timeouts and thresholds
// jest.config.jsmodule.exports = { testTimeout: 10000, // a hung test fails instead of blocking the pipeline coverageReporters: ['json', 'json-summary', 'text-summary'], coverageThreshold: { global: { lines: 80, branches: 70, functions: 85 }, './src/payments/': { lines: 95 }, }, reporters: ['default', 'jest-junit'],};The same thresholds now apply locally and in CI. Note that they apply to the whole run, so sharded runs need the merge step in Milestone 2.
Milestone 2 - Run unit tests in shards and gate on merged coverage
Each shard covers only part of the code, so per-shard coverage is meaningless. Run shards without a threshold, merge, then gate once.
jobs: unit-test: runs-on: ubuntu-latest strategy: fail-fast: false matrix: shard: [1, 2, 3, 4] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' cache: npm - run: npm ci - name: Run shard ${{ matrix.shard }} of 4 run: > npx jest --testPathPattern=unit --shard=${{ matrix.shard }}/4 --coverage --coverageThreshold='{}' - uses: actions/upload-artifact@v4 if: always() with: name: coverage-shard-${{ matrix.shard }} path: coverage/coverage-final.json retention-days: 7 coverage-gate: needs: unit-test runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' cache: npm - run: npm ci - uses: actions/download-artifact@v4 with: pattern: coverage-shard-* path: shards - name: Merge and enforce coverage run: | mkdir -p .nyc_output for dir in shards/*; do cp "$dir/coverage-final.json" ".nyc_output/$(basename "$dir").json" done npx nyc report --reporter=text-summary \ --check-coverage --lines 80 --branches 70 --functions 85Four shards finish in roughly a quarter of the time, and one gate decides on the combined result.
Milestone 3 - Run integration tests against real services
integration-test: needs: unit-test runs-on: ubuntu-latest services: postgres: image: postgres:15-alpine env: POSTGRES_DB: payment_test POSTGRES_USER: testuser POSTGRES_PASSWORD: testpass ports: - 5432:5432 options: >- --health-cmd "pg_isready -U testuser" --health-interval 10s --health-timeout 5s --health-retries 5 redis: image: redis:7-alpine ports: - 6379:6379 options: >- --health-cmd "redis-cli ping" --health-interval 10s --health-retries 5 env: DATABASE_URL: postgresql://testuser:testpass@localhost:5432/payment_test REDIS_URL: redis://localhost:6379 NODE_ENV: test steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' cache: npm - run: npm ci - run: npm run db:migrate - run: npm run db:seed:test - name: Run integration tests run: npx jest --testPathPattern=integration --runInBandThe service containers start fresh for every run, with synthetic data only. --runInBand runs tests one at a time so they do not collide on shared tables.
Milestone 4 - Publish test results on the pull request
report: needs: [unit-test, integration-test] if: always() runs-on: ubuntu-latest permissions: checks: write pull-requests: write steps: - uses: actions/download-artifact@v4 with: pattern: junit-* path: junit - name: Publish test results # pin third-party actions to a full commit SHA in production uses: EnricoMi/publish-unit-test-result-action@v2 with: files: junit/**/*.xmlEach test job should upload its junit.xml as an artifact named junit-<job>, so failures appear as annotations on the pull request.
Milestone 5 - Verify each deployment with smoke tests and roll back
smoke-test-staging: needs: deploy-staging runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Wait for the service to answer run: | curl --fail --silent --show-error \ --retry 10 --retry-delay 5 --retry-connrefused \ https://staging.payments.example.in/health - name: Run smoke tests env: BASE_URL: https://staging.payments.example.in run: npm run test:smoke - name: Roll back on failure if: failure() run: | kubectl rollout undo deployment/payment-api -n payment-api-staging kubectl rollout status deployment/payment-api -n payment-api-stagingThe retry loop replaces a fixed sleep, so the job waits only as long as needed. If you release with Argo Rollouts, abort the rollout instead of using rollout undo.
Milestone 6 - Detect and quarantine flaky tests
A flaky test passes and fails on the same code. Fix the cause first: shared state, time dependence, ordering, or real network calls. While you fix it, quarantine it so it cannot block everyone.
// jest.setup.js - short-term retry for known-flaky files onlyif (process.env.RETRY_FLAKY === 'true') { jest.retryTimes(2);} - name: Stable tests (block on failure) run: npx jest --testPathIgnorePatterns='flaky' flaky-quarantine: runs-on: ubuntu-latest continue-on-error: true # reports, but never blocks steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: '20' cache: npm - run: npm ci - run: RETRY_FLAKY=true npx jest --testPathPattern='flaky'Track every quarantined test with an owner and a due date. Compare results across runs, and investigate any test that fails more than about 5 percent of the time.
Milestone 7 - Find the slowest tests
npx jest --json --outputFile=results.jsonjq -r '.testResults[] | "\(.endTime - .startTime) \(.name)"' results.json | sort -rn | head -10The ten slowest files are usually the best candidates to speed up or split into more shards.
RememberJest's
--shardsplits by test file, so balance depends on how evenly your slowest files spread. Revisit the shard count when the suite grows.
SecurityIntegration tests must never point at a production or production-like database holding real user data. Use ephemeral service containers with synthetic seed data and separate credentials, and keep any real keys out of test config.
Production Best Practices & Common Pitfalls
- Run the fastest tests first so a mistake fails in seconds, not after the slowest suite.
- Enforce coverage on the merged result, and add diff coverage for new code where your tools support it.
- Keep end-to-end tests few and use them as post-deploy verification, not the main gate.
- Set a test timeout so a hung test fails instead of blocking the pipeline.
- Treat flaky tests as bugs with owners. Quarantine, fix, or delete them, never ignore them.
- Pin third-party actions to a full commit SHA, and avoid unpinned references such as
@main. - Upload reports with
if: always()so failures are always inspectable.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| Run only unit tests | npx jest --testPathPattern=unit |
| Run with coverage | npx jest --coverage |
| Run one file | npx jest path/to/file.spec.js |
| Run one shard locally | npx jest --shard=1/4 |
| Run tests for changed files | npx jest --changedSince=origin/main |
| Watch mode while developing | npx jest --watch |
| Symptom | Check | What to look for |
|---|---|---|
| Coverage gate fails on shards | Per-shard threshold | Gate must run on merged coverage |
| Integration tests hit DB errors | Service health and port | Container not ready or port clash |
| Tests pass locally, fail in CI | Node version and env vars | Version or config drift |
| Smoke test fails right after deploy | Readiness wait | Service not ready before the first call |
| Pipeline always green | continue-on-error usage |
It is set on a blocking job |