# Testing in pipelines: lint, unit, integration and the gate

The checks that decide what may merge: a linter, fast unit tests with a coverage threshold, integration tests against the real app and a database, and required status checks.

Course: [CI/CD Pipelines](https://devops.rajeev.pro/courses/cicd), lesson 5. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/cicd/05-testing-in-pipelines

## What you will learn

- Order checks from fastest to slowest so failures show up in seconds
- Lint JavaScript with ESLint and read what it reports
- Run unit tests with a coverage threshold that fails the build when coverage drops
- Write integration tests that start the real app, and give them a database with service containers
- Make the jobs required status checks so nothing red can merge
- Keep tests reliable, and deal with flaky ones instead of re-running them

## Fastest checks first

Without an ordered test pipeline, a slow end-to-end failure can waste a developer's wait while a simple typo sits
undetected. A good pipeline runs cheap checks first, then spends more time only when earlier checks pass. That
does not mean skipping broader tests; it means choosing where each test gives the fastest useful feedback. In
this lesson, you'll add lint, unit and integration checks and make the passing status a merge gate.

> **Figure.** The checks on a pull request, from fastest to slowest. Lint, about 20 seconds: catches typos, undefined variables and unused code. Unit tests with coverage, about 30 seconds: checks each function, and fails if coverage drops below 80 percent. Both run in parallel. Integration tests, a few minutes: start the real app and a Postgres service container, and test over HTTP; they run only if lint and unit pass. All three are required status checks in the ruleset for main, so the merge button stays disabled until every one is green.
>
> Lint and unit tests in parallel, integration only after both pass. All three are required, so red can't merge.

| Check             | Takes        | Catches                                                |
| ----------------- | ------------ | ------------------------------------------------------ |
| Lint              | seconds      | typos, undefined names, unused code, risky patterns    |
| Unit tests        | seconds      | wrong logic in a function                              |
| Integration tests | minutes      | parts that don't work together: HTTP, database, config |
| End-to-end tests  | many minutes | a real user flow through the whole system              |

Many fast unit tests, fewer integration tests, a handful of end-to-end tests: the **test pyramid**. Upside
down, the pipeline gets slow and flaky.

## Linting: the cheapest check

A **linter** reads code without running it. For JavaScript that's **ESLint**:

```sh
$ npm install --save-dev eslint@9 @eslint/js@9 globals
```

```js
// eslint.config.js
import js from '@eslint/js'
import globals from 'globals'

export default [
  js.configs.recommended,
  { languageOptions: { globals: globals.node } },
]
```

On a file with a typo in a variable name, it fails with exactly what's wrong:

```sh
$ npx eslint .
src/bad.js
  3:26  error  'sum' is assigned a value but never used  no-unused-vars
  4:10  error  'totl' is not defined                     no-undef

✖ 2 problems (2 errors, 0 warnings)
$ echo $?
1
```

That bug (`return totl` instead of `sum`) would have crashed the first request in production. Every
language has its linter: Ruff for Python, golangci-lint for Go, ShellCheck for shell, hadolint for
Dockerfiles, actionlint for workflows (lesson 2). Run formatters (Prettier, Black) in check mode too, so
style never shows up in review.

Linting is a cheap first filter because it can find mistakes without starting a server or database. Configure
the same command developers run locally, and make CI fail on the linter's non-zero exit code. A formatter checks
layout; a linter checks patterns and likely errors. They complement each other, but neither proves the program's
behavior is correct. Keep the rules focused enough that developers can act on each failure.

## Unit tests and coverage

**Unit tests** call one function or module directly and check the result: fast, precise, no network.
**Coverage** measures which lines your tests executed. A threshold makes the build fail if it drops:

```sh
$ node --test --experimental-test-coverage --test-coverage-lines=80 'test/*.test.js'
ℹ Error: 69.23% line coverage does not meet threshold of 80%.
ℹ start of coverage report
ℹ  app.js   |  69.23 |    87.50 |  100.00 | 12-19
```

The last column lists uncovered lines: 12 to 19, the `/price` route. One more unit test covers it:

```js
test('GET /price answers with the total, or 400 for a bad amount', async () => {
  const server = createApp().listen(0)
  const { port } = server.address()
  const ok = await fetch(`http://localhost:${port}/price?amount=100`)
  assert.deepEqual(await ok.json(), { total: 118 })
  const bad = await fetch(`http://localhost:${port}/price?amount=-1`)
  assert.equal(bad.status, 400)
  server.close()
})
```

```sh
$ npm run test:coverage
ℹ pass 4
ℹ fail 0
ℹ  app.js   |  96.15 |    90.91 |  100.00 | 19
```

Coverage says what **ran**, not whether it was checked properly: a test with no assertions still counts.
Use the threshold to stop coverage sliding down, and code review to judge the tests themselves.

## Integration tests: the real thing

**Integration tests** run the app the way production does and talk to it from outside. This one starts the
real server as a separate process and waits for `/health` before testing:

```js
// test/integration/api.test.js
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { spawn } from 'node:child_process'

const PORT = 4567
const base = `http://localhost:${PORT}`
let server

before(async () => {
  server = spawn(process.execPath, ['src/server.js'], { env: { ...process.env, PORT: String(PORT) } })
  for (let i = 0; i < 50; i++) {
    try {
      if ((await fetch(`${base}/health`)).ok) return
    } catch {
      // not listening yet: wait and retry
    }
    await new Promise((r) => setTimeout(r, 100))
  }
  throw new Error('server did not start within 5 seconds')
})

after(() => server.kill())

test('GET /price returns the total with tax', async () => {
  const res = await fetch(`${base}/price?amount=100`)
  assert.equal(res.status, 200)
  assert.deepEqual(await res.json(), { total: 118 })
})

test('unknown paths return 404', async () => {
  assert.equal((await fetch(`${base}/nope`)).status, 404)
})
```

```sh
$ node --test 'test/integration/*.test.js'
✔ GET /price returns the total with tax (310.217185ms)
✔ GET /price rejects a bad amount with 400 (31.433313ms)
✔ unknown paths return 404 (15.854698ms)
```

Note the quotes and the pattern: `node --test test/integration/` (a folder) finds nothing and fails. Keep
unit and integration tests in separate scripts so each job runs only its own:

```sh
$ npm pkg set scripts.test="node --test 'test/*.test.js'" \
    scripts.test:integration="node --test 'test/integration/*.test.js'" \
    scripts.test:coverage="node --test --experimental-test-coverage --test-coverage-lines=80 'test/*.test.js'"
```

### Service containers: a real database in CI

When the app needs a database, don't mock it in integration tests: start a real one next to the job with
a **service container**:

```yaml
integration:
  needs: [lint, unit]
  runs-on: ubuntu-latest
  services:
    postgres:
      image: postgres:17
      env:
        POSTGRES_PASSWORD: test
      ports: ['5432:5432']
      options: >-
        --health-cmd "pg_isready -U postgres"
        --health-interval 5s
        --health-timeout 5s
        --health-retries 10
  env:
    DATABASE_URL: postgres://postgres:test@localhost:5432/postgres
  steps:
    - uses: actions/checkout@v7
    - uses: actions/setup-node@v7
      with:
        node-version: 22
        cache: npm
    - run: npm ci
    - run: npm run test:integration
```

The health check makes GitHub wait until Postgres accepts connections before the first step runs. The
database exists only for this job, so every run starts empty and tests can't depend on leftovers. The
password is a throwaway for a container that lives a few minutes, which is why it can sit in the file.

## Required status checks: the gate

Checks only protect `main` if they're **required**. In _Settings → Rules → Rulesets_, edit the rule for the
default branch, enable **Require status checks to pass**, and add each job by name: `lint`, `unit`,
`integration`. Turn on **Require branches to be up to date** too, so a pull request is tested against the
current `main`, not the one it started from.

Now a pull request with a failing test shows _Merging is blocked_, and the merge button stays disabled
until every required check is green. Jobs skipped because a `needs` failed count as **not passed**.

> **Flaky tests are bugs.** A test that fails one run in ten and passes on re-run trains the whole team to ignore red, and then a real failure gets merged. Common causes: timing (`sleep` instead of waiting for a condition, like the health loop above), tests sharing state or depending on order, real time and time zones, and the network. Fix the cause; if you can't today, quarantine the test with a linked issue, never a silent retry.

> **Video.** [GitHub Branch Protection and Required Status Checks](https://www.youtube.com/watch?v=YzZa8DumDm8&t=90s) (Backend Deep Dives)

## Mission: Put a real gate in front of main

Give shop-api a full test pipeline: ESLint, unit tests with an 80% coverage threshold, and integration tests that start the real server, in that order of cost. Make all three required on main, then prove a pull request with a failing test can't be merged.

- You need: The shop-api repository from the earlier lessons
- You'll have: A blocked pull request, then a green one that merges

```sh
$ npm install --save-dev eslint@9 @eslint/js@9 globals
$ nano eslint.config.js                          # the config from this lesson
$ mkdir -p test/integration && nano test/integration/api.test.js
$ npm pkg set scripts.lint="eslint ." \
    scripts.test="node --test 'test/*.test.js'" \
    scripts.test:integration="node --test 'test/integration/*.test.js'" \
    scripts.test:coverage="node --test --experimental-test-coverage --test-coverage-lines=80 'test/*.test.js'"
$ npm run lint && npm run test:coverage && npm run test:integration
$ nano .github/workflows/ci.yml                  # lint and unit in parallel, integration after both
$ actionlint && git add . && git commit -m "ci: lint, unit with coverage, integration" && git push
$ git switch -c test/gate && sed -i 's/118)/119)/' test/app.test.js
$ git commit -am "test: break a test on purpose" && git push -u origin test/gate && gh pr create --fill
$ gh pr checks
```

After adding the three jobs as required checks, the pull request shows **unit** failing and _Merging is
blocked_; **integration** is skipped because it needs unit. Revert the change, push, and the merge button
turns green.

## Try it

- Add ESLint to a project and put a typo in a variable name to see `no-undef` catch it.
- Run tests with `node --test --experimental-test-coverage` and find the lines no test reaches.
- Set `--test-coverage-lines=80` and watch the run fail when coverage is too low.
- Add a Postgres service container to a job and connect to it with `pg_isready -h localhost`.
- In your ruleset for main, add lint, unit and integration as required status checks.
- Open a pull request with a failing test and check that the merge button is blocked.

## Quiz

1. Why run the linter before the integration tests?
   - Linters are more important
   - **It fails in seconds on mistakes that would waste minutes of slower jobs; cheapest checks first** (answer)
   - Integration tests need lint output
   - GitHub requires that order
   Why: Fast feedback is the point of CI. Lint and unit tests catch most problems in under a minute; slow jobs run only when those pass.

2. What does --test-coverage-lines=80 do?
   - Runs 80 tests
   - **Fails the test run if less than 80% of lines are executed by the tests** (answer)
   - Shows 80 lines of output
   - Skips 80% of tests
   Why: A threshold stops coverage quietly sliding down. It measures what ran, not whether it was checked properly, so it complements good tests rather than replacing them.

3. What is a service container in GitHub Actions?
   - A way to deploy
   - **A container, such as Postgres, started next to the job for its duration, so tests can use a real dependency** (answer)
   - A GitHub-hosted database
   - A runner type
   Why: Health checks make the job wait until the service is ready. It is destroyed with the job, so every run starts clean.

4. A test fails about one run in ten, and passes on re-run. What do you do?
   - Click re-run until it is green
   - **Treat it as a bug: find the cause (timing, shared state, order) and fix it, or quarantine it with an issue** (answer)
   - Delete it
   - Increase the timeout everywhere
   Why: A flaky test teaches everyone to ignore red. That is how real failures get merged.

5. How do you stop pull requests with failing tests from being merged?
   - Ask people nicely
   - **Add the CI jobs as required status checks in the ruleset for main** (answer)
   - Make the repository private
   - Delete failing branches
   Why: Required checks must pass before GitHub enables the merge button. Add each job by its name.

## Resources

- [ESLint: getting started](https://eslint.org/docs/latest/use/getting-started) (ESLint)
- [Node.js test runner](https://nodejs.org/api/test.html) (Node.js)
- [GitHub Docs: about service containers](https://docs.github.com/en/actions/tutorials/use-containerized-services/use-docker-service-containers) (GitHub Docs)
- [GitHub Docs: about status checks](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/about-status-checks) (GitHub Docs)
- [Martin Fowler: the practical test pyramid](https://martinfowler.com/articles/practical-test-pyramid.html) (martinfowler.com)
