Skip to main content

Testing and QA · Intermediate · 22 min

Build a CI quality gate for pull requests

By Padding · Updated 18 Nov 2026
node:26 (Debian) · Node.js 26 · Vitest 5.1.2 · Playwright 1.65.1 · GitHub Actions

You will have a GitHub Actions workflow that runs lint, type checks, sharded unit tests, integration tests and a smoke end-to-end test on every pull request, reports the JUnit results in the run summary and blocks merging through one required check.

On this page

A quality gate is the set of checks a pull request must pass before it can merge. A good one is strict and fast at the same time: it catches the mistakes that matter and gives an answer before the author has switched to something else. A slow gate gets worked around. A gate that anyone can ignore is only advice.

The trick is to choose what runs where. On every pull request you run the cheap, high-signal checks in order of speed: lint and types in seconds, unit tests in seconds, integration tests in a minute or so, and a handful of end-to-end tests that prove the main journey works. The full browser suite, slow tests and anything flaky go to a nightly run, where a failure opens a conversation instead of blocking a colleague.

In this tutorial you build a small bill-splitting app in TypeScript with all four layers of checks, write each check's results as JUnit XML, and wire them into two workflows: pr-gate.yml for pull requests and nightly.yml for the rest. One job, Quality gate, collects the results, so branch protection needs to require only that one check. It builds on /tutorials/run-node-tests-in-github-actions, which covers npm ci, caching and matrices from the start.

Step 1 · Create the sample app

The app splits a bill held in minor units (kobo, cents, pesewas) so the shares always add back up to the total. Working in whole minor units avoids floating-point rounding, which matters for any app that handles money. Make a throwaway project and install the tools at exact versions, so every run of the gate uses the same ones:

Bash
mkdir quality-gate-demo
cd quality-gate-demo
git init -b main
npm init -y
npm pkg set type=module
npm install --save-dev --save-exact vitest@5.1.2 vite@8.4.0 @playwright/test@1.65.1 typescript@6.0.3 eslint@10.15.0 @eslint/js@10.0.1 typescript-eslint@8.74.0 @types/node@26.6.11
mkdir -p src tests/unit tests/integration tests/e2e scripts
printf 'node_modules\nreports\nplaywright-report\ntest-results\n' > .gitignore

TypeScript is pinned at 6.0.3 rather than the newer 7.x line because typescript-eslint 8.74 supports TypeScript only below 6.1. Check typescript-eslint.io/users/dependency-versions before you upgrade either one.

Write the function and a small HTTP server around it. Node.js 26 runs .ts files directly by stripping the types, so there is no build step:

Bash
cat > src/split.ts <<'TS'
export type Split = { each: number[]; total: number }

// Split a bill held in minor units (kobo, cents) so the shares add up exactly.
export function splitBill(total: number, people: number): Split {
  if (!Number.isInteger(total) || total < 0) {
    throw new RangeError('total must be a whole number of minor units')
  }
  if (!Number.isInteger(people) || people < 1) {
    throw new RangeError('people must be at least 1')
  }
  const base = Math.floor(total / people)
  const remainder = total % people
  const each = Array.from({ length: people }, (_, i) => (i < remainder ? base + 1 : base))
  return { each, total }
}
TS

cat > src/server.ts <<'TS'
import { createServer, type Server } from 'node:http'
import { splitBill } from './split.ts'

const page = `<!doctype html>
<html lang="en">
  <head><meta charset="utf-8"><title>Bill splitter</title></head>
  <body>
    <h1>Bill splitter</h1>
    <form id="split">
      <label>Total in minor units <input name="total" value="1000"></label>
      <label>People <input name="people" value="3"></label>
      <button>Split</button>
    </form>
    <output id="result"></output>
    <script>
      document.getElementById('split').addEventListener('submit', async (event) => {
        event.preventDefault()
        const data = new URLSearchParams(new FormData(event.target))
        const res = await fetch('/api/split?' + data)
        const body = await res.json()
        document.getElementById('result').textContent = res.ok ? body.each.join(' + ') : body.error
      })
    </script>
  </body>
</html>`

export function buildServer(): Server {
  return createServer((req, res) => {
    const url = new URL(req.url ?? '/', 'http://localhost')
    if (url.pathname === '/') {
      res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
      res.end(page)
      return
    }
    if (url.pathname === '/api/split') {
      try {
        const result = splitBill(Number(url.searchParams.get('total')), Number(url.searchParams.get('people')))
        res.writeHead(200, { 'content-type': 'application/json' })
        res.end(JSON.stringify(result))
      } catch (error) {
        res.writeHead(400, { 'content-type': 'application/json' })
        res.end(JSON.stringify({ error: (error as Error).message }))
      }
      return
    }
    res.writeHead(404)
    res.end()
  })
}

if (import.meta.main) {
  const port = Number(process.env.PORT ?? 3000)
  buildServer().listen(port, () => console.log(`listening on ${port}`))
}
TS

buildServer() returns the server without starting it. The integration tests in a later step use that to start it on a free port of their own. import.meta.main is true only when the file is run directly, so importing it from a test does not open port 3000.

Check it worked

Start the server:

Bash
PORT=3000 node src/server.ts

It prints listening on 3000. In a second terminal, in the same folder, ask the API for a split:

Bash
curl -s 'http://127.0.0.1:3000/api/split?total=1000&people=3'

You see {"each":[334,333,333],"total":1000}: the one leftover kobo goes to the first person. Stop the server with Ctrl+C.

Step 2 · Add the fastest checks: lint and types

Lint and type checks need no running code and finish in seconds, so they go first. If a pull request fails here, there is no point spending runner minutes on browsers. Add the configuration and two scripts:

Bash
cat > tsconfig.json <<'JSON'
{
  "compilerOptions": {
    "target": "es2024",
    "module": "nodenext",
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "erasableSyntaxOnly": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["src", "tests", "scripts", "*.ts"]
}
JSON

cat > eslint.config.js <<'JS'
import js from '@eslint/js'
import tseslint from 'typescript-eslint'

export default tseslint.config(
  { ignores: ['reports/', 'playwright-report/', 'test-results/'] },
  js.configs.recommended,
  tseslint.configs.recommended,
)
JS

npm pkg set scripts.lint="eslint ." scripts.typecheck="tsc"

noEmit makes tsc a checker only. erasableSyntaxOnly rejects TypeScript features that Node.js cannot strip, such as enum, so code that type-checks also runs.

Check it worked

Bash
npm run lint
npm run typecheck

Both finish with no output after the script name. Now prove they catch something. Add a file with an unused variable and a type error, run both checks, then delete it:

Bash
printf "const unused = 1\nexport const answer: number = 'forty-two'\n" > src/oops.ts
npm run lint || echo "lint failed, as expected"
npm run typecheck || echo "typecheck failed, as expected"
rm src/oops.ts

ESLint reports 'unused' is assigned a value but never used and tsc reports Type 'string' is not assignable to type 'number'. Both exit non-zero, which is what fails a CI step.

Step 3 · Write unit and integration tests that produce JUnit XML

Unit tests call splitBill directly. Integration tests start the real HTTP server and talk to it with fetch, so they cover parsing, status codes and JSON as well. Vitest projects keep the two sets apart so CI can run them as separate jobs:

Bash
cat > vitest.config.ts <<'TS'
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    projects: [
      { test: { name: 'unit', include: ['tests/unit/**/*.test.ts'] } },
      { test: { name: 'integration', include: ['tests/integration/**/*.test.ts'] } },
    ],
    reporters: ['default', 'junit'],
    outputFile: { junit: process.env.JUNIT_FILE ?? 'reports/junit.xml' },
  },
})
TS

cat > tests/unit/split.test.ts <<'TS'
import { describe, expect, it } from 'vitest'
import { splitBill } from '../../src/split.ts'

describe('splitBill', () => {
  it('splits evenly when it can', () => {
    expect(splitBill(900, 3).each).toEqual([300, 300, 300])
  })

  it('gives the leftover minor units to the first people', () => {
    expect(splitBill(1000, 3).each).toEqual([334, 333, 333])
  })

  it('always adds back up to the total', () => {
    const { each } = splitBill(12345, 7)
    expect(each.reduce((a, b) => a + b, 0)).toBe(12345)
  })
})
TS

cat > tests/unit/validation.test.ts <<'TS'
import { describe, expect, it } from 'vitest'
import { splitBill } from '../../src/split.ts'

describe('splitBill input checks', () => {
  it('rejects zero people', () => {
    expect(() => splitBill(1000, 0)).toThrow(RangeError)
  })

  it('rejects fractions of a minor unit', () => {
    expect(() => splitBill(10.5, 2)).toThrow('whole number')
  })
})
TS

cat > tests/integration/api.test.ts <<'TS'
import { afterAll, beforeAll, expect, it } from 'vitest'
import type { AddressInfo } from 'node:net'
import { buildServer } from '../../src/server.ts'

const server = buildServer()
let base = ''

beforeAll(async () => {
  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
  base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
})

afterAll(() => new Promise<void>((resolve) => server.close(() => resolve())))

it('returns the split as JSON', async () => {
  const res = await fetch(`${base}/api/split?total=1000&people=3`)
  expect(res.status).toBe(200)
  expect(await res.json()).toEqual({ each: [334, 333, 333], total: 1000 })
})

it('answers 400 with a message for bad input', async () => {
  const res = await fetch(`${base}/api/split?total=1000&people=0`)
  expect(res.status).toBe(400)
  expect((await res.json()).error).toMatch('at least 1')
})
TS

npm pkg set scripts.test:unit="vitest run --project unit" scripts.test:integration="vitest run --project integration"

Two details carry into CI. Listening on port 0 lets the operating system pick a free port, so integration jobs never collide over a fixed one. And JUNIT_FILE lets each job name its own report, because several jobs writing reports/junit.xml would overwrite each other once the reports are merged.

JUnit XML is the common format here: almost every test runner can write it and almost every CI tool can read it, so the gate does not care which runner produced a report.

Sharding splits one test set across parallel jobs. --shard=1/2 runs the first half of the test files and --shard=2/2 the second. Run the unit tests the way CI will, as two shards:

Bash
JUNIT_FILE=reports/unit-1.xml npm run test:unit -- --shard=1/2
JUNIT_FILE=reports/unit-2.xml npm run test:unit -- --shard=2/2
JUNIT_FILE=reports/integration.xml npm run test:integration

Check it worked

Each run ends with JUNIT report written to and a path. Shard 1 runs three tests and shard 2 runs two: Vitest shards by file, not by test. List the reports and look at the counts in one:

Bash
ls reports
head -n 3 reports/integration.xml

You see integration.xml, unit-1.xml and unit-2.xml, and the integration file's <testsuites> line shows tests="2" failures="0".

Step 4 · Add a smoke end-to-end test

End-to-end tests are the slowest and most fragile layer, so the pull request gate runs only the few that prove the main journey works. Tag those @smoke. Everything else in the browser suite runs nightly:

Bash
cat > playwright.config.ts <<'TS'
import { defineConfig, devices } from '@playwright/test'

export default defineConfig({
  testDir: 'tests/e2e',
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 1 : 0,
  reporter: [['list'], ['junit', { outputFile: 'reports/e2e.xml' }]],
  use: { baseURL: 'http://127.0.0.1:3100', trace: 'on-first-retry' },
  projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
  webServer: {
    command: 'node src/server.ts',
    url: 'http://127.0.0.1:3100',
    env: { PORT: '3100' },
    reuseExistingServer: !process.env.CI,
  },
})
TS

cat > tests/e2e/split.spec.ts <<'TS'
import { expect, test } from '@playwright/test'

test('splits a bill in the browser', { tag: '@smoke' }, async ({ page }) => {
  await page.goto('/')
  await expect(page.getByRole('heading', { name: 'Bill splitter' })).toBeVisible()
  await page.getByRole('button', { name: 'Split' }).click()
  await expect(page.locator('#result')).toHaveText('334 + 333 + 333')
})

test('shows the error for zero people', async ({ page }) => {
  await page.goto('/')
  await page.getByLabel('People').fill('0')
  await page.getByRole('button', { name: 'Split' }).click()
  await expect(page.locator('#result')).toHaveText('people must be at least 1')
})
TS

npm pkg set scripts.test:smoke="playwright test --grep @smoke" scripts.test:e2e="playwright test"
npx playwright install --with-deps chromium

webServer starts the app before the tests and stops it afterwards. forbidOnly fails the run if someone leaves a test.only behind, which would otherwise quietly skip the rest of the suite. One retry in CI, with a trace recorded on that retry, gives you evidence when a test is flaky without hiding it: Playwright reports a test that passed only on retry as flaky.

The Chromium download is over 100 MB. On a metered or prepaid connection, run the install once and keep the browser cache (~/.cache/ms-playwright on Linux) between projects rather than reinstalling.

Check it worked

Bash
npm run test:smoke
npx playwright test --list

The smoke run reports 1 passed and writes reports/e2e.xml. The list shows two tests: the smoke test and the error-message test, which only the nightly run picks up.

Step 5 · Turn the reports into a pull request summary

A red cross tells the author that something failed. A table of results with the failing test names tells them what, without opening five job logs. GitHub Actions shows any Markdown a step appends to the file named in GITHUB_STEP_SUMMARY on the run's summary page, which the pull request links to. This script reads every JUnit file it is given and writes that table. It uses only Node.js built-ins, so the gate job needs no npm ci:

Bash
cat > scripts/junit-summary.ts <<'TS'
// Turn JUnit XML files into a Markdown table for the GitHub job summary.
// Usage: node scripts/junit-summary.ts reports/*.xml
import { appendFileSync, readFileSync } from 'node:fs'
import { basename } from 'node:path'

const attr = (tag: string, name: string) => Number(tag.match(new RegExp(`${name}="(\\d+)"`))?.[1] ?? 0)
const unescape = (s: string) =>
  s.replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&quot;', '"').replaceAll('&apos;', "'").replaceAll('&amp;', '&')

const rows = ['| Report | Tests | Failed | Skipped |', '| --- | --- | --- | --- |']
const failed: string[] = []

for (const file of process.argv.slice(2)) {
  const xml = readFileSync(file, 'utf8')
  const suites = [...xml.matchAll(/<testsuite\s[^>]*>/g)].map((m) => m[0])
  const tests = suites.reduce((n, s) => n + attr(s, 'tests'), 0)
  const failures = suites.reduce((n, s) => n + attr(s, 'failures') + attr(s, 'errors'), 0)
  const skipped = suites.reduce((n, s) => n + attr(s, 'skipped'), 0)
  rows.push(`| ${basename(file, '.xml')} | ${tests} | ${failures} | ${skipped} |`)
  // Each chunk is one test case, from its attributes up to </testcase>.
  for (const chunk of xml.split('<testcase').slice(1)) {
    const testcase = chunk.split('</testcase>')[0]
    const name = testcase.match(/^\s(?:[^>]*\s)?name="([^"]*)"/)?.[1]
    if (name !== undefined && /<(failure|error)[\s>/]/.test(testcase)) failed.push(unescape(name))
  }
}

let text = `### Test results\n\n${rows.join('\n')}\n`
if (failed.length) text += `\nFailing tests:\n\n${failed.map((name) => `- ${name}`).join('\n')}\n`

console.log(text)
if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, text)
TS

npm run lint
npm run typecheck
node scripts/junit-summary.ts reports/*.xml

Two details in the test-case loop matter. The runners order attributes differently: Vitest writes classname before name, Playwright writes name first, so the pattern asks for whitespace before name= and never picks up the end of classname=. And a test case can hold other elements, such as <properties>, before its <failure>, so the script checks everything up to </testcase> rather than only what comes straight after the opening tag. These patterns are enough for the reports these two runners write. If you feed it reports from other tools, swap them for an XML parser.

Check it worked

The output is a table with four rows, e2e, integration, unit-1 and unit-2, and 0 in every Failed cell. Now add a failing test, run the unit tests into their own report, and summarise only that report:

Bash
cat > tests/unit/broken.test.ts <<'TS'
import { expect, it } from 'vitest'
import { splitBill } from '../../src/split.ts'

it('puts the leftover on the last person', () => {
  expect(splitBill(1000, 3).each).toEqual([333, 333, 334])
})
TS
JUNIT_FILE=reports/unit-broken.xml npm run test:unit || echo "unit tests failed, as expected"
node scripts/junit-summary.ts reports/unit-broken.xml

The table shows 1 under Failed, and a Failing tests list names puts the leftover on the last person. Remove the test and its report before you go on:

Bash
rm tests/unit/broken.test.ts reports/unit-broken.xml

Step 6 · Write the pull request workflow

Each layer becomes a job. Lint and types run first; the three test jobs wait for them with needs and then run in parallel. The unit tests use a matrix to run both shards at once. Every job uploads its JUnit file as an artifact, and the last job collects them all:

Bash
mkdir -p .github/workflows
cat > .github/workflows/pr-gate.yml <<'YAML'
name: PR gate

on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read

concurrency:
  group: pr-gate-${{ github.ref }}
  cancel-in-progress: true

jobs:
  static:
    name: Lint and types
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm run typecheck

  unit:
    name: Unit tests (shard ${{ matrix.shard }} of 2)
    needs: static
    runs-on: ubuntu-latest
    timeout-minutes: 5
    strategy:
      fail-fast: false
      matrix:
        shard: [1, 2]
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - run: npm run test:unit -- --shard=${{ matrix.shard }}/2
        env:
          JUNIT_FILE: reports/unit-${{ matrix.shard }}.xml
      - uses: actions/upload-artifact@v7
        if: ${{ !cancelled() }}
        with:
          name: junit-unit-${{ matrix.shard }}
          path: reports/

  integration:
    name: Integration tests
    needs: static
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - run: npm run test:integration
        env:
          JUNIT_FILE: reports/integration.xml
      - uses: actions/upload-artifact@v7
        if: ${{ !cancelled() }}
        with:
          name: junit-integration
          path: reports/

  smoke:
    name: Smoke end-to-end
    needs: static
    runs-on: ubuntu-latest
    timeout-minutes: 8
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - run: npx playwright install --with-deps chromium
      - run: npm run test:smoke
      - uses: actions/upload-artifact@v7
        if: ${{ !cancelled() }}
        with:
          name: junit-e2e
          path: reports/
      - uses: actions/upload-artifact@v7
        if: ${{ failure() }}
        with:
          name: playwright-traces
          path: test-results/
          retention-days: 7

  gate:
    name: Quality gate
    if: ${{ always() }}
    needs: [static, unit, integration, smoke]
    runs-on: ubuntu-latest
    timeout-minutes: 3
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 26
      - uses: actions/download-artifact@v8
        with:
          pattern: junit-*
          path: reports
          merge-multiple: true
      - name: Write the test summary
        run: |
          shopt -s nullglob
          files=(reports/*.xml)
          if [ ${#files[@]} -gt 0 ]; then
            node scripts/junit-summary.ts "${files[@]}"
          else
            echo "No JUnit reports were produced." >> "$GITHUB_STEP_SUMMARY"
          fi
      - name: Fail unless every check passed
        if: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') }}
        run: |
          echo "One or more checks did not pass: ${{ join(needs.*.result, ', ') }}"
          false
YAML

What each choice is for:

  • Order of speed. needs: static means a pull request with a lint error fails in about a minute and never starts a browser. The cost is that tests start a little later. If your lint job is slow, drop the needs lines and let everything run at once.
  • Sharding. The matrix creates two unit jobs that each run half the files. With five tests it makes no difference; it pays off once one job takes several minutes. Add shards when the slowest job, not the total, is what makes the gate slow.
  • Caching. cache: npm in setup-node keeps npm's download cache between runs, keyed on package-lock.json. Playwright's own documentation recommends against caching browsers in CI: restoring the cache takes about as long as downloading, and the system libraries that --with-deps installs cannot be cached anyway.
  • Timeouts. timeout-minutes stops a hung job early instead of at GitHub's default of six hours. Set each one a little above the job's normal time.
  • Uploads that survive failure. if: ${{ !cancelled() }} uploads the report even when the tests fail, which is when you need it most. Traces are uploaded only on failure and kept for seven days.
  • One gate job. if: ${{ always() }} makes Quality gate run and report even when an earlier job fails or is skipped, and its last step fails unless every job it needs succeeded. This is the only check branch protection has to know about, so you can rename, add or shard jobs without editing the repository settings.

Check it worked

Check the workflow with actionlint, a checker for workflow files from github.com/rhysd/actionlint. Download a release for your system (version 1.7.12 here) as shown in /tutorials/github-actions-first-workflow, then run it in the repository:

Bash
actionlint
echo "actionlint exit code: $?"

No output and exit code 0 mean the YAML and the expressions such as ${{ matrix.shard }} passed its checks. actionlint also checks the shell in each run block, but only when it finds shellcheck on your PATH; install shellcheck from your package manager if you want that check too. Then run the commands the jobs run, in the same order, from a clean install:

Bash
rm -rf node_modules reports
npm ci
npm run lint
npm run typecheck
JUNIT_FILE=reports/unit-1.xml npm run test:unit -- --shard=1/2
JUNIT_FILE=reports/unit-2.xml npm run test:unit -- --shard=2/2
JUNIT_FILE=reports/integration.xml npm run test:integration
npm run test:smoke
node scripts/junit-summary.ts reports/*.xml

Every command exits cleanly and the summary shows four reports with no failures.

Step 7 · Move the slow checks to a nightly run

Some checks are worth running but not worth making every author wait for: the full browser suite, more browsers, long-running or load tests, and dependency audits. Put them in a scheduled workflow. Here it runs every test, unsharded, at 01:30 UTC each night, and can also be started by hand:

Bash
cat > .github/workflows/nightly.yml <<'YAML'
name: Nightly

on:
  schedule:
    - cron: '30 1 * * *'
  workflow_dispatch:

permissions:
  contents: read

jobs:
  full:
    name: Full test suite
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: 26
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm run typecheck
      - run: npm run test:unit
        env:
          JUNIT_FILE: reports/unit.xml
      - run: npm run test:integration
        env:
          JUNIT_FILE: reports/integration.xml
      - run: npx playwright install --with-deps chromium
      - run: npm run test:e2e
      - name: Write the test summary
        if: ${{ !cancelled() }}
        run: node scripts/junit-summary.ts reports/*.xml
      - uses: actions/upload-artifact@v7
        if: ${{ !cancelled() }}
        with:
          name: nightly-reports
          path: |
            reports/
            test-results/
          retention-days: 14
YAML

Scheduled runs use the workflow file on the default branch, so nightly.yml starts running only after it is merged to main. GitHub can delay scheduled runs at busy times, and disables them in public repositories with no activity for 60 days. Decide who reads a red nightly run, or nobody will.

Check it worked

Bash
actionlint
npm run test:e2e

actionlint prints nothing for either file. The full browser run reports 2 passed: the smoke test plus the error-message test the pull request gate leaves out.

Step 8 · Make the gate required

Commit everything and push it to a repository you own. Replace YOUR-USER/YOUR-REPO with yours:

Bash
git add .
git commit -m "Add CI quality gate"
Bash
git remote add origin git@github.com:YOUR-USER/YOUR-REPO.git
git push -u origin main

The push runs PR gate once on main. That first run matters: a check name appears in the branch protection settings only after it has reported at least once.

Now require it. In the repository's settings, find the branch rules (named Branches or Rules, depending on the current layout), add a rule for main, turn on "Require status checks to pass before merging", and pick Quality gate. Turn on the option to require branches to be up to date as well, so a pull request is tested against the latest main and not against what main looked like when the branch was made.

With the GitHub CLI you can set the same thing through the branch protection API. Write the settings to a file first:

Bash
cat > protection.json <<'JSON'
{
  "required_status_checks": { "strict": true, "checks": [{ "context": "Quality gate" }] },
  "enforce_admins": true,
  "required_pull_request_reviews": null,
  "restrictions": null
}
JSON
node -e "JSON.parse(require('node:fs').readFileSync('protection.json', 'utf8')); console.log('protection.json is valid JSON')"

This call replaces any protection already set on main, including required reviews. Read the current settings with gh api repos/YOUR-USER/YOUR-REPO/branches/main/protection first and copy anything you want to keep into the file:

Bash
gh api -X PUT repos/YOUR-USER/YOUR-REPO/branches/main/protection --input protection.json
rm protection.json

Do not add paths filters to pr-gate.yml. A required check from a workflow that never starts stays "Expected" forever and blocks the merge.

Check it worked

Open a pull request that adds a failing test, such as the broken.test.ts file from earlier. The pull request's checks list shows Lint and types passing, Unit tests (shard 1 of 2) or (shard 2 of 2) failing, and Quality gate failing, and the merge button is blocked. The Quality gate job's summary page shows the results table with the failing test's name. Fix or remove the test and push again: every check turns green and you can merge.

To keep the gate under ten minutes, check the timings now and then with gh run list --workflow "PR gate", which shows each run's duration. When the gate creeps past ten minutes, look at the slowest job first: add a shard, move tests that do not need a browser out of the end-to-end set, or move a slow check to the nightly run.

Next steps

  • Decide what coverage numbers belong in the gate, and which do not: /tutorials/measure-code-coverage-without-chasing-100-percent.
  • When the gate gets slow, measure before you shard: /tutorials/speed-up-a-slow-test-suite.
  • Review the workflow basics behind this one: /tutorials/run-node-tests-in-github-actions.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.