Sub topic 4
Running automated tests on every change
This chapter covers what a pipeline should test on each change, how to order those tests, and how to deal with the errors that make test results untrustworthy. It assumes you have read the earlier chapters on continuous integration and build automation. You should also be comfortable with Git, the command line, and reading simple YAML. You should have run a test suite for a small application before.
Why tests are the core of CI
Continuous integration (CI) merges changes often. A merge only helps if you can tell quickly whether the change broke something. Automated tests give that answer. Without them, a CI server only proves the code compiles.
A pipeline runs the tests on every push and every pull request. This gives you three things:
- Fast feedback. The author hears about a failure minutes after the push, while the change is still fresh in their mind.
- A shared gate. The result does not depend on one person's machine or on someone remembering to run the tests.
- A record. Each run is logged against a specific commit, so you can see when a test started failing.
The test step in the minimal workflow from the topic plan is one line:
name: ci
on:
push:
branches: [main]
pull_request:
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 testThe step npm test runs your test command. The runner treats any non-zero exit code as a failure. That marks the step failed, stops the job, and marks the commit or pull request as failing. Everything else in this chapter builds on that exit-code contract.
Kinds of tests in a pipeline
Different tests answer different questions. They also differ in speed and in how often they fail for reasons unrelated to your change.
| Kind | What it checks | Typical speed | Typical stage |
|---|---|---|---|
| Static checks (lint, type check) | Style problems and type errors without running the code | Seconds | First |
| Unit tests | One function or class in isolation | Seconds to a few minutes | Early |
| Integration tests | Several components together, such as code plus a database | Minutes | Middle |
| End-to-end tests | The whole application through its real interface | Many minutes | Late |
| Smoke tests | A few critical paths on a deployed environment | Seconds to minutes | After deploy |
Static checks are not tests in the strict sense, but they belong in the same early gate because they are cheap and catch real mistakes.
The test pyramid
The test pyramid is a guideline for how many tests of each kind to write. You write many unit tests, fewer integration tests, and few end-to-end tests. Lower levels are fast and precise. Higher levels are slow and realistic, but when they fail, the cause is harder to locate.
A suite with the shape reversed (mostly end-to-end tests) is slow and flaky. It also makes every failure expensive to diagnose.
Ordering tests: fail fast
The rule is to run the cheapest, most informative checks first. If lint fails in ten seconds, there is no reason to wait twenty minutes for end-to-end tests. In a pipeline you express this with separate jobs and the needs keyword.
name: ci-tests
on:
push:
branches: [main]
pull_request:
jobs:
lint:
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 run lint
unit:
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
integration:
needs: [lint, unit]
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 run test:integrationThis example assumes your package.json defines lint and test:integration scripts. Adjust the names to match your project.
lint and unit have no dependency on each other, so they run in parallel. integration waits for both. If either fails, integration is skipped and you save its runtime.
Parallel jobs trade runner capacity for wall-clock time. Each job repeats checkout and install, so splitting too finely can cost more than it saves. The cache: npm option reduces that cost by reusing downloaded packages between runs.
Making tests reliable
A pipeline is only useful if people believe its result. Most trust problems come from a small set of causes.
Flaky tests
A flaky test is one that sometimes passes and sometimes fails on the same code. Common causes are:
- Timing assumptions, such as waiting a fixed 100 ms for something asynchronous.
- Shared state between tests, such as a database row one test leaves behind for the next.
- Test order dependence, where a test passes only if another ran first.
- External services, such as a real network call to a third-party API.
- Uncontrolled inputs, such as the current date or a random seed.
Flaky tests are costly because people learn to click "re-run" instead of reading the failure. Once that habit forms, real failures get re-run too.
Practical responses:
- Fix the cause. Wait for a condition, not a duration. Give each test its own data. Replace the real network with a fake.
- If you cannot fix it now, quarantine the test. Move it to a separate non-blocking job and file a ticket so it does not disappear.
- Track which tests fail intermittently, so you can prioritize.
Automatic retries hide flakiness rather than remove it. Use them sparingly and make sure retried tests are still reported.
Environment parity
Tests that pass on a laptop and fail in CI usually differ in environment: operating system, tool version, environment variables, or installed services. Reduce the gap by pinning versions (the node-version: 20 line above), using npm ci instead of npm install so the lockfile is respected, and running services in containers.
For integration tests that need a database, GitHub Actions lets a job declare a service container:
name: ci-db
on:
pull_request:
jobs:
integration:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: test-only-password
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 5s
--health-timeout 5s
--health-retries 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run test:integration
env:
DATABASE_URL: postgres://postgres:test-only-password@localhost:5432/postgresThe health check makes the job wait until the database accepts connections before the tests start. Without it, the first tests can fail because the database is still starting. The password here is a throwaway value for a database that exists only during the run. Real credentials belong in the secret store, covered in a later chapter.
Test results as data
A bare pass/fail tells the author little. Make the runner publish more detail:
- Print the failing test name and assertion message in the log.
- Upload test reports and screenshots as artifacts so they survive after the runner is gone.
- Record coverage, and treat it as a signal rather than a goal. A coverage percentage says which lines ran, not whether the assertions checked anything useful.
Gating changes with test results
Running tests does not stop a bad change unless something enforces the result. Two settings do this work:
- Branch protection. Configure the repository so a pull request cannot merge until named checks pass. Without this, a red build is only advice.
- Required reviews and up-to-date branches. Requiring the branch to be current with
mainmeans the tests ran against what will actually be merged.
Also watch for a subtle failure mode: a check that is required but never reports. If a path filter or a skipped job means the check does not run, the merge can be blocked forever or, depending on configuration, allowed through. Check how your platform treats skipped required checks.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Passes locally, fails in CI | Different tool versions, missing environment variables, or a missing service | Pin versions, use `npm ci`, declare services in the job |
| Fails only sometimes | Flaky test: timing, shared state, or order dependence | Isolate state, wait on conditions, quarantine if needed |
| Pipeline takes 40 minutes | Slow tests run first, nothing runs in parallel, no caching | Reorder by cost, split jobs, cache dependencies |
| Red build is ignored | No branch protection, or frequent false failures | Require checks, remove flaky tests |
| Tests pass but a bug ships | Missing test coverage for that behavior | Add a regression test with the fix |
The last row has a standard habit attached. When you fix a bug, first write a test that fails because of it, then make it pass. The test stays in the suite and the same bug cannot return unnoticed.
Summary of working rules
- Run tests on every push and pull request, and make the exit code decide the result.
- Order checks from cheapest to most expensive, and let early failures stop later work.
- Keep most tests at the unit level, with fewer integration and end-to-end tests.
- Treat flaky tests as defects. Fix or quarantine them rather than re-running.
- Match the CI environment to what you run locally and in production.
- Enforce results with branch protection so a failing check blocks the merge.
Exercise
A pipeline has one job that runs lint, unit tests, and a 25-minute end-to-end suite in that order, and the job stops at the first failure. Developers complain that a typo caught by lint still takes a long time to report on some runs. Why might that happen, and how would you restructure the pipeline?
Show answer
Lint runs first, so a lint failure should stop the job quickly, provided each step fails on a non-zero exit code and nothing before it is slow. The delay likely comes from setup (checkout, dependency install without caching) or from a step order that is not what the team thinks it is. Another cause is that failures in other checks, such as the end-to-end suite, are what developers are waiting on after fixing the lint error. The better structure is separate jobs: lint and unit in parallel, then the end-to-end job with needs: [lint, unit]. Add dependency caching, so each job's setup is short, and make sure branch protection requires all of these jobs.
Exercise
A test in your suite fails about one run in ten. Developers have started re-running the pipeline whenever it fails. Name two likely causes and describe what you would do this week.
Show answer
Likely causes include a fixed-duration wait on asynchronous work, shared database state left by another test, test order dependence, a call to a real external service, or an uncontrolled input such as the current time. This week, reproduce the failure by running the test repeatedly and in random order, fix the underlying cause (wait on a condition, isolate the data, or fake the external call), and if the fix takes longer, move the test to a non-blocking quarantine job with a ticket. Stop the re-run habit, because it will also hide real failures.