Skip to content
All posts

How to increase test coverage in a legacy codebase with Danger JS

Three automated pull request rules raised test coverage on a client codebase by 12 to 16 points in two months, with no big rewrite. Here's how they work, with a working example repo.

Matt Claffey · 4 min read

Most teams agree that more tests would be good. The hard part is making it happen without stopping feature work for a coverage sprint or a rewrite. A coverage target on a dashboard tends to drift, because nothing checks it at the moment code changes: in the pull request.

On a recent client project I set out to make better tests the default rather than a separate project, so that every pull request leaves the code a little better tested than it found it. Two months after adding Danger JS to every PR, the numbers looked like this.

Statements +12.3 points, branches +14.7, functions +15.7, and 2.5 times as many unit tests

If you'd rather read the code than the post, the whole setup is in a working example repo: dangerjs-example. The slides are also available as a PDF download.

Danger JS reviews every PR before a person does

Danger JS runs in CI, reads the pull request (the diff, the description, any reports your build produced) and leaves a comment. It can also fail the build. Here it runs in GitHub Actions straight after Jest has run with coverage turned on.

PR opened, Jest runs with coverage, Danger reads the diff and the report, then comments or fails the build

The whole entry point is five lines:

// dangerfile.js
import checkForTestFiles from './danger/checkForTestFiles.js'
import checkCoverageReporting from './danger/coverageReport.js'

checkForTestFiles()
checkCoverageReporting()

Those two functions hold three rules. Only the first one can block a merge.

Rule 1: every changed source file needs a test file

If a PR adds or edits Basket.tsx, Danger looks for Basket.test.tsx. If there isn't one, the PR goes red and the comment lists each file that needs a test.

const changedFiles = [...danger.git.modified_files, ...danger.git.created_files]

// For each changed source file, look for a matching test, in the PR or already in the repo
const testPatterns = ['ts', 'tsx'].flatMap((extension) => [
  `${dir}/${baseFileName}.test.${extension}`,
  `${dir}/__tests__/${baseFileName}.test.${extension}`,
])

if (filesWithoutTests.length > 0) {
  fail(`Missing tests for the following files:\n${fileList}`)
}

A few details made this rule stick:

  • Touch it, test it. It only checks the files in the diff, so old code gets tests as people work on it. Nobody has to stop and backfill the whole codebase.
  • Sensible skips. Generated GraphQL, stories, type files, icons and route files are ignored, and every ignore rule has a comment saying why.
  • It matches how people work. A .ts hook tested from a .tsx file still counts, whether the test sits next to it or in __tests__.
  • An escape hatch. Writing #skip-danger in the PR description skips the checks for a genuine emergency, and it shows up in the review.

The rule gates on the presence of a test file, not on a percentage. That's simple to understand and hard to argue with.

Rule 2: coverage for each changed file, right in the PR

Jest already writes a coverage report. Danger turns it into a table for just the files in the diff, marked against the project's thresholds, so reviewers see the weak spot without opening a report.

A PR comment listing each changed file with its statement, branch and function coverage

This rule never blocks. It's information, and that was deliberate: visibility changed behaviour without making the gate noisy.

Rule 3: a PR comment asks the developer to raise the bar

This is the ratchet. Danger compares overall coverage against the thresholds in the Jest config. When a metric is more than 5 points above its threshold, it posts a warning suggesting the developer raises it.

Coverage climbs, Danger warns, the developer bumps the Jest config in the same PR, and the new floor fails CI below it

Danger's warning: branches 66% against a 50% threshold, functions 67% against 50%. Consider increasing the Jest coverage thresholds

Nobody has to remember to do it, and each raise becomes a new floor that Jest enforces on every later PR. Over the two months, the team raised the thresholds from 40–50% to 53–66% off the back of that comment.

The results

Unit test files went from 353 on the day Danger JS was added to 637 two months later. Before Danger, the codebase gained about 55 test files a month. After, about 130.

Unit test files from June to November: about 55 new a month before Danger JS, about 130 a month after

Measured from the Jest coverage summary for the whole codebase, on the commit before Danger was added and on the latest main:

Metric Before After Change
Statements 41.9% 54.2% +12.3 pts
Branches 51.6% 66.3% +14.7 pts
Functions 51.7% 67.4% +15.7 pts
Lines 46.1% 58.4% +12.3 pts
Unit tests 3,071 7,566 2.5×

The codebase grew by about 20% over the same period, so coverage rose while the team kept shipping features.

Four lessons

  1. Gate on presence, not percentage. Fail a PR for a missing test file. It's simple to understand and hard to argue with.
  2. Show, don't block. Put the coverage numbers in the PR as information. Visibility changes behaviour without making the gate noisy.
  3. Start low, ratchet up. Set thresholds just below today's numbers and let a PR comment say when it's time to raise them.
  4. Write down every skip. Each ignore rule carries a reason, and there's one visible escape hatch, so exceptions stay rare and reviewable.

The key to this approach is that it never asks anyone to tackle the whole problem at once. Nobody is handed a backlog of untested files. Instead it encourages good citizen behaviour: as a developer, you write tests for the changes you've made, and the codebase gets better one pull request at a time.

It isn't bulletproof. If you add code to a file that already has a test file, rule 1 still passes, even if the new code isn't tested. That's where rule 2 earns its place: the file's coverage drops in the PR table, so the gap is visible to the author and the reviewer.

Try it yourself

The example repo has the dangerfile, the GitHub Action and a small demo codebase, plus two open pull requests that show the rules working:

  • PR #1 adds a file with no test, and Danger fails it.
  • PR #2 adds tests for legacy code, and Danger posts the coverage table and the nudge to raise the thresholds.

Danger JS is free and runs in the CI you already have. You don't need a quality initiative. You need a default.

If you'd like help setting up quality gates on your codebase, get in touch.