xtest

CI/CD and DevOps Testing

CI/CD Pipeline Testing

This course teaches how to design, build, and maintain automated testing inside a continuous integration and continuous delivery pipeline. You will learn how to structure a test suite so it runs fast and reliably on every commit, which test types belong at which pipeline stage, how to set quality gates that block a bad build from reaching production, and how to keep a growing pipeline from becoming slow or flaky. The course works through real pipeline configurations using tools such as GitHub Actions, Jest, and Playwright, so you can apply what you learn directly to a real project. By the end, you will be able to set up a pipeline that lints, unit tests, integration tests, and end-to-end tests a codebase automatically, report results clearly to a team, and troubleshoot the most common causes of pipeline failure and flakiness.

Intermediate · By the Xtest team · About 33 minutes to read

Introduction

Software teams that ship often cannot rely on a human tester clicking through an application before every release. Continuous integration and continuous delivery (CI/CD) move testing into the pipeline itself, so that every commit is built, tested, and evaluated automatically before it is allowed anywhere near production. Done well, this turns testing from a bottleneck into a safety net that lets a team move fast with confidence. Done poorly, a pipeline full of slow, flaky, or badly organized tests becomes something developers route around rather than trust.

This course walks through the full lifecycle of pipeline testing: what a pipeline should check and in what order, how to pick the right mix of unit, integration, and end-to-end tests for each stage, how to wire real tools like Jest and Playwright into a pipeline such as GitHub Actions, and how to keep an eye on a pipeline's health over time so it stays fast and trustworthy as the codebase grows. You will see complete, runnable configuration examples rather than abstract theory, and you will practice building and debugging a pipeline yourself through hands-on exercises.

By the end of the course you will understand not just how to write a test, but how to make testing part of the rhythm of delivering software: every commit checked, every failure caught early, and every pipeline run giving the team a clear, fast answer about whether the code is safe to ship.

Foundations of CI/CD Pipeline Testing

Why Testing Belongs Inside the Pipeline

In a CI/CD setup, every commit triggers a pipeline: a sequence of automated steps that builds the code, runs tests against it, and decides whether it is safe to move forward. This is a fundamental shift from testing as a separate phase that happens before a release, to testing as a continuous check that happens dozens or hundreds of times a day. The goal is to catch a problem within minutes of it being introduced, while the person who wrote the change still remembers exactly what they did and can fix it immediately, rather than weeks later during a release crunch.

What a Pipeline Actually Checks

A typical pipeline runs several kinds of checks in sequence: static analysis and linting to catch obvious code issues, unit tests to check small pieces of logic in isolation, integration tests to check that pieces work together, and end-to-end tests that drive the application the way a real user would. Each of these has a different speed and a different job, and a well-designed pipeline runs the fastest, cheapest checks first so that an obvious mistake is reported in seconds rather than after a 20-minute end-to-end run.

Quality Gates

A quality gate is a point in the pipeline where a result decides what happens next: if the unit tests fail, the pipeline stops and nothing deploys; if end-to-end tests fail against a staging environment, the release to production is blocked. Gates give a team an objective, consistent rule instead of a judgment call made under release pressure. Designing good gates means deciding, in advance and as a team, what must pass before code moves forward, and making sure every gate's result is visible to whoever needs to act on it.

Getting these foundations right, fast feedback, the right test at the right stage, and clear gates, is what separates a pipeline a team trusts from one they start ignoring. The rest of this course builds directly on these ideas: picking the right automated testing strategy, wiring real tools into a pipeline, and keeping the whole system healthy as it grows.

What Makes a Good CI/CD Test

A test that lives in a pipeline has different requirements from a test a developer runs by hand on their own machine. First, it needs to be fast: a pipeline that takes an hour to tell a developer whether their change broke something will get ignored or run less often, which defeats the purpose of continuous integration. Second, it needs to be deterministic: given the same code, it should produce the same result every time, with no randomness, no dependence on the time of day, and no reliance on an external service that might be slow or unavailable. A test that sometimes fails for no reason related to the code, commonly called a flaky test, is worse than no test at all, because it trains the team to ignore failures.

Third, a good pipeline test is isolated: it sets up its own data, does not depend on another test having run first, and cleans up after itself so it does not leave behind state that breaks a later run. Fourth, it should fail with a clear, specific message that tells the reader exactly what went wrong and where, rather than a generic error that sends someone hunting through logs. Finally, a pipeline test should be independent of the machine it runs on: it should not assume a particular file path, a particular timezone, or a tool that happens to be installed on one developer's laptop but not on the pipeline's build agent. Meeting all of these properties takes deliberate design, and it is far easier to build them in from the start than to retrofit them into a large, slow, flaky suite later.

Pipeline Stages and Quality Gates

Most CI/CD pipelines are organized into a sequence of stages, each one a gate the code must pass through before the next stage even begins. A typical sequence looks like: checkout and build the code, run static analysis and linting, run unit tests, run integration tests, deploy to a staging environment, run end-to-end tests against staging, and finally deploy to production, sometimes with a further check after that. Each stage answers a narrower, more expensive question than the one before it: linting catches style and obvious logic issues in seconds, unit tests catch logic errors in individual functions within a minute or two, integration tests catch problems between components, and end-to-end tests catch problems a real user would actually hit, at the cost of being the slowest stage to run.

The key design decision for each gate is what counts as a pass. A strict gate blocks all progress on any failure, which is right for anything that touches production directly. A softer gate might let a team flag a known, tracked failure and proceed anyway, which can be useful for a flaky or low-priority test while it is being fixed, but should be used sparingly since it is easy for a team to quietly accumulate ignored failures this way. Ordering stages so the cheapest, fastest gate runs first means a broken build is reported in seconds rather than after a long, expensive end-to-end run has already started, which keeps the whole pipeline fast and keeps developers willing to run it often.

name: CI

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Lint
        run: npm run lint

      - name: Unit tests
        run: npm test -- --coverage

      - name: Install Playwright browsers
        run: npx playwright install --with-deps

      - name: End-to-end tests
        run: npx playwright test

A GitHub Actions workflow that runs on every push and pull request. It checks out the code, installs dependencies with caching, lints the code, runs unit tests with coverage, then installs Playwright's browsers and runs the end-to-end test suite. Each step acts as a gate: if linting or unit tests fail, the workflow stops before the slower Playwright step even starts.

Tips

  • Order pipeline steps from fastest to slowest so an obvious failure is reported in seconds, not after a long end-to-end run has already started.
  • Cache dependencies between pipeline runs so the pipeline is not reinstalling the same packages on every single commit.
  • Give every test a clear, specific failure message so whoever sees a red pipeline knows exactly what broke without digging through logs.

Common pitfalls

  • Running a slow, full end-to-end suite on every single commit stalls every pull request and tempts the team to skip the pipeline. Solution: run a small smoke subset of end-to-end tests on every push, and the full suite on a schedule or just before merging.
  • A test that depends on another test running first, or on data left over from a previous run, will pass locally and then fail unpredictably in CI. Solution: have every test create and clean up its own data so it can run completely on its own, in any order.

Automated Testing Strategies in CI/CD

A pipeline that runs every test on every commit will eventually become the slowest part of your delivery process unless you are deliberate about what runs where and how. The classic test pyramid still holds: a large base of fast, isolated unit tests that run in seconds, a smaller layer of integration tests that check how modules or services cooperate, and a thin top layer of end-to-end tests that drive the real application the way a user would. Each layer catches different bugs, and each layer costs more time and more infrastructure the higher up the pyramid you go. The job of a pipeline designer is to keep that shape honest as the codebase grows, rather than letting end-to-end tests multiply because they feel more 'real.'

Two practical techniques keep a growing suite fast. First, parallelization: independent suites or shards of a suite run in separate jobs or containers at the same time, so wall-clock time stays flat even as the number of tests climbs. Second, disciplined test data management: each test sets up its own data, cleans up after itself, and never depends on state left behind by another test, so tests can run in any order and in parallel without interfering with each other.

End-to-end checks are still necessary for the handful of journeys that matter most, like checkout or sign-up. For those, xtest is a hosted web application where you describe a test in plain English, pick a device, and an AI test agent carries it out while you watch; its REST API can start a suite's run from a pipeline and the run's result can fail the build. Keep that layer small and reserve it for flows where only driving the real UI will do.

Shaping the Test Pyramid

The test pyramid is a guide for deciding where a new check belongs, not a rulebook to apply mechanically. A unit test should cover a single function or class in isolation, with no network, filesystem or database involved, so it runs in milliseconds and fails with a precise, local reason. An integration test checks that two or more real pieces, such as a service and its database, or two internal services, actually agree on a contract; it is slower and needs more setup, so it should exist where a unit test cannot prove the collaboration works. An end-to-end test drives the whole system the way a real user or client would, through the UI or the public API, and it is the slowest and most fragile layer because it depends on every component underneath it being up and correctly configured.

The common mistake is writing end-to-end tests for logic that a unit test could cover just as well, which inflates pipeline time without adding confidence. A useful question before adding any test: if this breaks, is this the cheapest, fastest-to-diagnose layer that would catch it? If a unit test would catch the same bug, write the unit test. Reserve end-to-end coverage for the small number of journeys whose failure would actually hurt the business, such as sign-up, checkout or a core workflow unique to the product, and keep that top layer thin on purpose.

Parallelizing Suites to Control Pipeline Time

As a suite grows, running it as one long serial job turns every pull request into a wait. The fix is to split the suite across multiple jobs that run at the same time, then combine their results into one pass or fail signal for the pipeline. Most CI systems support this with a matrix or shard strategy: the same job definition runs several times, each instance given a different slice of the test files, and the pipeline only turns green once every shard has reported success.

Splitting work evenly matters as much as splitting it at all. If one shard happens to contain the handful of slow integration tests and the rest finish in seconds, that one shard becomes the new bottleneck, so suites are often split by historical run time rather than by file count alone. Independent suites, meaning tests that do not share mutable state such as a single shared database row, are what make parallel runs safe; a parallel run exposes any hidden coupling between tests immediately, because two tests racing against the same data will intermittently fail. Keeping unit and integration suites separate from a slower end-to-end suite also lets fast feedback land first: a developer can see unit test results within a minute while the slower checks continue in the background, rather than waiting for everything to finish before learning that a typo broke a basic function.

jobs:
  unit-tests:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        shard: [1, 2, 3, 4]
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npx jest --shard=${{ matrix.shard }}/4

A GitHub Actions matrix splits a Jest unit test suite into four shards that run in parallel jobs; the pipeline only passes once all four shards finish successfully, keeping total run time close to that of the slowest single shard instead of the sum of all four.

const { seedDatabase, cleanDatabase } = require('./testUtils');

describe('order creation', () => {
  let testUserId;

  beforeEach(async () => {
    testUserId = await seedDatabase({ users: 1, orders: 0 });
  });

  afterEach(async () => {
    await cleanDatabase(testUserId);
  });

  test('creates an order for a seeded user', async () => {
    const order = await createOrder(testUserId, { item: 'widget', qty: 2 });
    expect(order.status).toBe('pending');
  });
});

Each test seeds its own isolated data before it runs and tears it down afterward, so the test can run in any order, alongside other tests, or in a parallel shard without colliding with data another test created.

Tips

  • Measure where your pipeline time actually goes before optimizing; splitting the wrong suite into shards saves little if a single slow job elsewhere is the real bottleneck.
  • Give every test its own data, created in setup and removed in teardown, so parallel and out-of-order runs stay repeatable.
  • Keep the end-to-end layer deliberately small and reserved for journeys where only driving the real application proves the system works; let unit and integration tests catch everything else earlier and faster.

Common pitfalls

  • Letting the end-to-end suite grow because it feels more trustworthy than a unit test: this makes the pipeline slow and brittle, so push coverage down to the fastest layer that can prove the same thing.
  • Sharing a single test database or fixture across tests that run in parallel: tests that write to the same rows will fail intermittently depending on execution order, so give each test its own seeded data instead of a shared fixture.

Integrating Test Automation Tools into Pipelines

A pipeline only earns its keep when it runs real tests on every change and stops the build the moment one fails. This section covers wiring tools like Jest, Playwright, and Selenium into GitHub Actions, GitLab CI, Jenkins, and CircleCI: installing the right runtime and browser binaries, triggering the test command as a pipeline step, waiting for it to finish, and reading its exit code to decide whether the build passes.

The same shape applies whether the suite runs inside the pipeline's own runner or on a separate hosted service that the pipeline merely triggers and polls. A hosted service needs a way to start a run, a way to ask whether it has finished, and a way to read the result, and the pipeline step fails the build unless the answer is a clean pass. xtest's documentation gives a ready script, written with curl and jq, that starts a suite from GitHub Actions, GitLab CI, Jenkins or CircleCI and fails the build unless every test passed, which saves writing that polling logic by hand.

Beyond simply running commands, a mature pipeline integration handles three concerns well: making the trigger step reliable across CI providers that each have their own syntax for steps, environment variables and secrets; keeping credentials out of logs and out of version control; and surfacing a clear, fast failure signal so a broken build is obvious within seconds of opening the pipeline's output, not buried in pages of console noise.

Triggering Suites and Failing the Build on Failure

Each CI system runs a job as a sequence of shell steps, so triggering Jest, Playwright, or Selenium is a matter of installing dependencies, installing any browser binaries the tool needs, and running the test command as one of those steps. The step's exit code is what matters: a non-zero exit code from the test runner should propagate to the job, and every major CI system fails the job automatically when a step's command exits non-zero, so there is usually nothing extra to configure beyond calling the test command directly.

Waiting for a result becomes more involved when the suite runs somewhere other than the CI runner itself, for example on a remote grid or a hosted service. In that case the pipeline step has to start the run, poll a status endpoint or command on an interval until the run reports finished, and only then inspect the pass or fail count before deciding the job's own exit code. A polling loop should have a timeout: a run that never reports back should fail the build after a sensible wait rather than hang the pipeline indefinitely, since a stuck pipeline blocks every other change behind it.

It is worth separating 'the tests ran and some failed' from 'the tests could not run at all', for example because a dependency failed to install or a service was unreachable. Both should fail the build, but distinguishing them in the log output saves time when someone is trying to work out what actually went wrong at two in the morning.

Authentication and Keeping Secrets Out of Logs

Any pipeline step that talks to a remote test grid, browser service, or hosted test runner needs credentials, and those credentials must never appear in plain text in the pipeline configuration file or in its printed output. Every CI system provides an encrypted secret store for this: GitHub Actions calls them repository or organization secrets, GitLab CI calls them CI/CD variables, Jenkins has its credentials store, and CircleCI has environment variables scoped to a project or context. A secret is referenced by name in the pipeline configuration and injected into the job's environment at run time, so the actual value is never written to the YAML or script file that lives in version control.

Two habits keep secrets out of logs even by accident. First, never echo or print an environment variable that holds a credential, since most CI systems do mask known secret values in their own output but cannot mask a value they do not know is sensitive, such as a key that gets concatenated into a larger string before being printed. Second, treat a token as scoped and replaceable: a leaked value should be revocable without touching anything else, which is why a hosted service's API key is generated per workspace rather than shared account-wide. xtest's own key is made in the dashboard under Setup, xtest API keys, starts with xtest_live_, is shown once at creation, and acts only in the workspace it was made for, which fits this same pattern of a scoped, revocable pipeline secret.

name: End-to-end tests
on: [push, pull_request]
jobs:
  playwright:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - run: npm ci
      - run: npx playwright install --with-deps
      - run: npx playwright test
        env:
          BASE_URL: ${{ secrets.STAGING_URL }}
          API_TOKEN: ${{ secrets.STAGING_API_TOKEN }}

A GitHub Actions job that installs dependencies and Playwright's browser binaries, then runs the test suite. The job fails automatically if `playwright test` exits with a non-zero status, and the BASE_URL and API_TOKEN values come from encrypted repository secrets rather than being written into the file.

#!/usr/bin/env bash
set -euo pipefail

npm ci
npx jest --ci --reporters=default --reporters=jest-junit
EXIT_CODE=$?

if [ "$EXIT_CODE" -ne 0 ]; then
  echo "Test suite failed, blocking deploy."
  exit "$EXIT_CODE"
fi

echo "All tests passed, proceeding."

A shell script, usable from Jenkins or CircleCI, that runs a Jest suite with `set -euo pipefail` so any failing command stops the script immediately, writes a JUnit report for the CI dashboard, and exits with the test runner's own status code so the pipeline job is marked failed on any test failure.

Tips

  • Pin the exact version of the test runner and browser binaries in the pipeline, not just in local development, so a pipeline failure is caused by a real regression and not a silently upgraded dependency.
  • Always set a timeout on any step that waits or polls for a remote result, so a hung service fails the build instead of blocking the whole pipeline indefinitely.
  • Store every credential, including staging URLs and tokens that feel harmless, in the CI system's secret store rather than in the pipeline file, since a public repository's history keeps every past commit.

Common pitfalls

  • Treating a test command's zero exit code on a partial run as a pass: a test runner that crashes before finishing can still exit 0 in some configurations, so check the reported test count, not only the exit code.
  • Printing environment variables for debugging and forgetting one holds a secret: route debug output through a step that explicitly excludes credential variable names, since a CI system can only mask secret values it already knows about.

Monitoring, Reporting, and Continuous Improvement in CI/CD Testing

A pipeline that passes today can quietly decay over months: runs get slower, a handful of tests start failing at random, and nobody notices until a release is blocked by a test nobody trusts anymore. Monitoring, reporting, and continuous improvement are the habits that keep a test suite worth running.

Three things deserve regular attention. First, pipeline duration: a suite that took three minutes last quarter and takes fifteen minutes now is quietly costing every developer who waits on it. Second, flakiness: tests that fail and pass on the same code without any change are the fastest way to make a team stop trusting CI results, which is worse than having no tests at all. Third, visibility: a failure buried in a build log that only one engineer reads defeats the purpose of automated testing. Results need to reach the people who can act on them, in a form they will actually read.

This section covers building lightweight monitoring around your pipeline (tracking duration and failure rate over time rather than guessing), setting up alerts that fire on the failures that matter without drowning the team in noise, and running a periodic review where you decide, test by test, whether it still earns its place: keep it, rewrite it, move it to a different stage (for example from the fast pre-merge suite to a slower nightly run), or delete it. Deleting a test that no longer protects anything is itself an improvement, since every test is a maintenance cost as well as a safety net.

The goal is not a perfect pipeline on day one. It is a pipeline that gets measurably better over time because someone is looking at the data and acting on it.

You cannot improve what you do not measure. Most CI systems expose a build duration and a pass/fail result for every run; the first step is simply collecting that data somewhere durable instead of letting it scroll past in a dashboard that only shows the last few runs.

A simple approach is to have your pipeline write one line per run (timestamp, branch, duration, pass or fail, number of tests) to a file or a lightweight time-series store, then review it weekly or monthly rather than reacting to every single run. Look for two patterns in particular. A steady upward creep in duration usually means tests have been added without anyone trimming the slow ones, or the suite has stopped running things in parallel the way it used to. A rising failure rate concentrated in a handful of tests, rather than spread evenly, is a strong sign of flakiness rather than a real regression.

It also helps to separate 'the pipeline is slow' from 'the pipeline is flaky'; they have different fixes. A slow pipeline is improved by running independent test groups in parallel, moving expensive end-to-end checks to a less frequent schedule, and caching dependencies between runs. A flaky pipeline is improved by finding the specific unreliable tests and fixing or removing them, not by adding more retries and hoping. Retries hide the symptom; they do not fix the underlying race condition, timing assumption, or shared test data that caused the flakiness in the first place.

Identifying and Taming Flaky Tests

A flaky test is one that fails and then passes again with no code change in between. Left alone, flaky tests train a team to ignore red builds, which is the opposite of what a test suite is supposed to do.

The first job is finding them. Running a suspect test multiple times in a row, either locally or as a dedicated CI job, is the fastest way to confirm flakiness before you spend time 'fixing' a test that was actually catching a real bug. Most causes fall into a short list: a test that waits a fixed number of milliseconds instead of waiting for a real condition, a test that depends on another test's leftover data, a test that assumes a specific order of execution, or a test that calls a real external service that is sometimes slow or unavailable.

Once found, a flaky test has three honest outcomes: fix the underlying timing or isolation problem, quarantine it in a separate job so it stops blocking merges while it is investigated, or delete it if it no longer tests anything useful. Quietly adding retries and moving on is the one outcome to avoid, since it makes the suite less trustworthy over time even while every individual run looks green. If you are running tests through a tool that replays saved steps rather than re-running everything from scratch, a saved step that stops working is itself worth watching: it usually means the page genuinely changed rather than that the test was flaky, and it deserves a look before you let an automatic repair through unreviewed.

Reporting Results Without Burying Them in Logs

A test result that only exists in a build log is, in practice, a test result nobody reads. Good reporting means failures reach the right people, in the right amount of detail, without requiring anyone to go digging.

At minimum, a CI pipeline should produce a machine-readable report (JUnit XML is the common format most CI dashboards and test frameworks already understand) so that failures show up as readable annotations in the pull request or build summary rather than as raw console text. Beyond that, a short daily or weekly summary, sent somewhere the team already looks, tends to get read far more reliably than a dashboard people have to remember to open. For a nightly schedule in particular, a report that leads with what broke, then gives a simple count of what passed, is far more useful than a wall of green checkmarks followed by a handful of failures you have to scroll to find. xtest's scheduled runs work this way: the morning email lists failures first, with the test and the step, then gives passes as a count and lists any automatic repairs waiting for approval, and by default it only arrives when something actually changed, so an unbroken string of identical passing nights does not fill up anyone's inbox.

Whatever the format, keep two things separate: a report that engineers read to debug a failure (which needs detail: logs, screenshots, stack traces) and a summary that a wider team reads to know whether things are healthy (which needs brevity: pass count, failure count, trend). Mixing the two produces a report too long for the people who just need the headline and too shallow for the people who need to fix the bug.

#!/usr/bin/env bash
# flaky-check.sh: run a suspect test N times and report how often it fails
TEST_FILE=$1
RUNS=${2:-10}
FAILS=0

for i in $(seq 1 "$RUNS"); do
  if ! npx jest "$TEST_FILE" --silent > /tmp/run_$i.log 2>&1; then
    FAILS=$((FAILS + 1))
    echo "Run $i: FAILED"
  else
    echo "Run $i: passed"
  fi
done

echo "\n$FAILS out of $RUNS runs failed for $TEST_FILE"
if [ "$FAILS" -gt 0 ] && [ "$FAILS" -lt "$RUNS" ]; then
  echo "This test looks flaky: it fails intermittently with no code change."
fi

A small script that reruns a single Jest test file several times in a row. A test that sometimes fails and sometimes passes across identical runs is flaky; this is a cheap way to confirm suspicion before spending time investigating or rewriting a test.

#!/usr/bin/env bash
# log-pipeline-run.sh: append one line per CI run to a CSV for trend review
TIMESTAMP=$(date -u +%Y-%m-%dT%H:%M:%SZ)
BRANCH=${CI_COMMIT_BRANCH:-local}
START=$(date +%s)

npx playwright test --reporter=junit --output=results.xml
STATUS=$?

END=$(date +%s)
DURATION=$((END - START))
TOTAL=$(grep -c '<testcase' results.xml)
FAILED=$(grep -c '<failure' results.xml)

echo "$TIMESTAMP,$BRANCH,$DURATION,$TOTAL,$FAILED,$STATUS" >> pipeline-history.csv

A script that runs a Playwright suite, parses the JUnit output for test and failure counts, and appends one row (timestamp, branch, duration, test count, failure count, exit status) to a CSV file. Reviewing that CSV weekly surfaces duration creep and rising failure rates long before they become a crisis.

Tips

  • Review pipeline duration and failure trends on a schedule (weekly or monthly) rather than only when someone complains; slow creep is easy to miss run by run.
  • When you find a flaky test, write down the suspected cause (timing, shared data, external dependency) before fixing it, so the fix addresses the real problem instead of just adding a retry.
  • Keep debugging-detail reports (logs, screenshots) separate from team-wide summaries (pass count, failure count); a report trying to serve both audiences usually serves neither well.
  • Revisit old tests periodically and be willing to delete ones that no longer protect anything real; a smaller trustworthy suite beats a large one nobody fully trusts.

Common pitfalls

  • Papering over flaky tests with automatic retries instead of fixing the underlying race condition or shared state; the test keeps passing in CI while quietly eroding confidence in every other result.
  • Sending every pipeline run's full output to the whole team, which trains people to ignore notifications; prefer a short summary that highlights failures first and only sends when something changed.
  • Letting the test suite only grow and never pruning it; tests that no longer match the product or that duplicate another test's coverage should be rewritten or retired, not left to slow the pipeline indefinitely.

Exercises

Exercise 1: Build a Staged CI Pipeline

In this exercise you will build a complete CI pipeline for a small sample application using GitHub Actions. The goal is to practice ordering pipeline stages correctly so that fast checks run before slow ones, and so that a failure at any stage stops the pipeline before wasting time on later stages. You will start from a basic Node.js project that already has a few Jest unit tests and a couple of Playwright end-to-end tests written. Your job is to write a workflow file that checks out the code, installs dependencies with caching enabled, runs a linter, runs the unit tests with coverage reporting turned on, and only then installs Playwright's browsers and runs the end-to-end tests. You should deliberately introduce a failing unit test at one point during the exercise and confirm that the pipeline stops before the end-to-end stage runs at all, then fix the test and confirm the full pipeline passes end to end. Pay attention to how long each stage takes, and think about what would happen to feedback time if the stages were run in the opposite order.

  1. Fork or clone the provided sample Node.js project with existing Jest and Playwright tests.
  2. Write a GitHub Actions workflow file with separate steps for checkout, dependency install, lint, unit test, and end-to-end test.
  3. Add dependency caching to the workflow using actions/setup-node's built-in npm cache option.
  4. Introduce a deliberately failing unit test, push the change, and confirm the pipeline stops before the end-to-end step runs.
  5. Fix the failing test, push again, and confirm every stage passes and the full pipeline completes.

Expected outcome: A working GitHub Actions workflow file that runs lint, unit tests, and end-to-end tests in the correct order, stops immediately on a unit test failure without running the slower end-to-end stage, and passes completely once the failing test is fixed.

Exercise 2: Diagnose and Fix a Flaky Test

Flaky tests are one of the most damaging problems a CI/CD pipeline can have, because they train a team to ignore red pipeline results. In this exercise you will be given a Playwright end-to-end test that fails intermittently, roughly one run in five, even though the application under test has no real bug. Your task is to investigate the pipeline logs and the test code to find the root cause of the flakiness, which in this case comes from the test clicking a button before the page has fully finished loading its data. You will fix the test by waiting for a specific, meaningful condition, such as an element becoming visible or a network request completing, rather than adding a fixed delay, and then run the test repeatedly to confirm it now passes consistently. Finally, you will write a short note explaining what caused the flakiness and why a fixed delay is a weaker fix than waiting for a specific condition, so the lesson is captured for the rest of the team.

  1. Run the provided flaky Playwright test ten times in a row and record how many times it fails.
  2. Read the test code and the application's page structure to identify the race condition causing the failure.
  3. Replace any fixed wait with a Playwright locator-based wait for the specific element or state the test actually depends on.
  4. Run the fixed test at least ten times in a row to confirm it passes consistently.
  5. Write a short explanation of the root cause and why waiting for a condition is more reliable than waiting for a fixed amount of time.

Expected outcome: A Playwright test that passes consistently across at least ten consecutive runs, along with a written explanation identifying the race condition that caused the original flakiness and why the fix resolves it.

Exercise 3: Add a Coverage Quality Gate

Quality gates turn a pipeline from a simple pass or fail check into a tool that enforces a team's actual standards. In this exercise you will add a code coverage gate to an existing pipeline so that a pull request is blocked if it drops overall test coverage below a set threshold. You will configure Jest to output a coverage report, set a minimum coverage threshold in Jest's configuration, and confirm that the pipeline fails when a change is introduced that is not covered by any test. You will then write a test that covers the new code, confirm coverage rises back above the threshold, and confirm the pipeline passes again. This exercise is meant to build intuition for how a gate can encode a policy, such as never shipping untested code, directly into the pipeline rather than relying on a person remembering to check.

  1. Add a coverageThreshold configuration to the project's Jest configuration file, setting a minimum percentage for statements, branches, functions, and lines.
  2. Add a small new function to the sample application with no accompanying test.
  3. Run the pipeline and confirm it fails because coverage has dropped below the configured threshold.
  4. Write a unit test that covers the new function.
  5. Run the pipeline again and confirm it now passes with coverage back above the threshold.

Expected outcome: A pipeline that fails when new, untested code drops coverage below the configured threshold, and passes again once a test is added for that code, demonstrating a working coverage-based quality gate.

Quiz

1. Why should the fastest checks, such as linting and unit tests, run before the slowest checks, such as end-to-end tests, in a CI/CD pipeline?

  1. So that an obvious failure is reported within seconds instead of after a long, expensive run has already completed
  2. Because end-to-end tests cannot be run inside a pipeline at all
  3. Because linting tools require the application to already be deployed
  4. Because unit tests are only meaningful after end-to-end tests have passed
Show answer

A. So that an obvious failure is reported within seconds instead of after a long, expensive run has already completed

Ordering pipeline stages from fastest to slowest means a developer finds out about an obvious mistake, such as a lint error or a broken unit test, within seconds rather than after waiting for a much longer end-to-end run to finish. This keeps feedback fast and keeps the pipeline worth running on every commit.

2. What is a flaky test?

  1. A test that sometimes passes and sometimes fails against the same code, for reasons unrelated to an actual bug
  2. A test that always fails until a bug is fixed
  3. A test that only checks the visual appearance of a page
  4. A test written in a scripting language instead of a compiled language
Show answer

A. A test that sometimes passes and sometimes fails against the same code, for reasons unrelated to an actual bug

A flaky test produces inconsistent results on the same code, often because of timing issues, shared state, or reliance on something outside the test's control. Flaky tests are harmful because they erode trust in the pipeline, leading teams to start ignoring failures that may actually be real.

3. What is a quality gate in a CI/CD pipeline?

  1. A point in the pipeline where a result decides whether the code is allowed to move forward to the next stage
  2. A firewall rule that blocks external traffic to the build server
  3. A manual code review performed after every deployment
  4. A tool that automatically fixes failing tests
Show answer

A. A point in the pipeline where a result decides whether the code is allowed to move forward to the next stage

A quality gate is a checkpoint, such as requiring all unit tests to pass or coverage to stay above a threshold, that must be satisfied before the pipeline continues to the next stage, such as deployment. Gates turn a team's standards into an automatic, consistent rule rather than a judgment call.

4. Why is isolating a test's data important for reliable CI/CD testing?

  1. Because a test that depends on data left behind by another test can pass locally and then fail unpredictably in the pipeline
  2. Because isolated tests run faster on every computer regardless of hardware
  3. Because pipelines automatically delete all test data after every run
  4. Because shared test data is required for end-to-end tests to work at all
Show answer

A. Because a test that depends on data left behind by another test can pass locally and then fail unpredictably in the pipeline

A test that relies on data set up by a previous test, or on a particular run order, is fragile: it may pass when run alone or in one order but fail when run in a pipeline where order or parallelism differs. Having each test set up and clean up its own data keeps results consistent.

5. According to the course, what does a coverage threshold gate in a pipeline actually enforce?

  1. That a pull request cannot be merged if it drops test coverage below a configured minimum percentage
  2. That every function in the codebase must have at least ten tests
  3. That the pipeline automatically writes new tests for uncovered code
  4. That end-to-end tests are skipped whenever unit test coverage is high
Show answer

A. That a pull request cannot be merged if it drops test coverage below a configured minimum percentage

A coverage threshold gate checks the percentage of code exercised by tests and fails the pipeline if a change drops that percentage below an agreed minimum. This encodes a team's policy, such as never shipping untested code, directly into the automated pipeline instead of relying on manual review.

Related docs

All courses