> ## Documentation Index
> Fetch the complete documentation index at: https://empirical.run/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Code coverage

> Measure which parts of your application code the end-to-end tests exercise, as an Istanbul HTML report

Empirical tests your deployed application as a black box, so coverage needs an instrumented build.
Your application team instruments the build and builds the report, and Empirical collects coverage
data during test runs:

1. **Instrument the application.** Add Istanbul to your bundler. This needs your application source,
   so your team does it.
2. **Collect coverage in tests.** Turn on coverage in the test fixtures. An Empirical agent can make
   this change.
3. **Build the report.** Download the coverage files from a run and build an HTML report with `nyc`.
   This also needs your application source.

## Instrument the application

This example uses Vite. Other bundlers need an equivalent Istanbul plugin. In your application
repository, install the plugin:

```sh theme={null}
npm install --save-dev vite-plugin-istanbul
```

Add the plugin to `vite.config.ts`. When tests run against a deployed URL rather than localhost, keep
`forceBuildInstrument: true` so production builds include the instrumentation:

```ts theme={null}
import { defineConfig } from "vite";
import istanbul from "vite-plugin-istanbul";

export default defineConfig({
  plugins: [
    istanbul({
      include: "src/*",
      exclude: ["node_modules", "test/"],
      extension: [".js", ".ts", ".tsx"],
      requireEnv: false,
      forceBuildInstrument: true,
    }),
  ],
});
```

## Collect coverage in tests

Coverage collection needs `@empiricalrun/playwright-utils` 0.43.0 or later. In the test fixture file,
pass `{ collectCoverage: true }` to `baseTestFixture`:

```ts theme={null}
import { test as base, expect as baseExpect } from "@playwright/test";
import { baseTestFixture, extendExpect } from "@empiricalrun/playwright-utils/test";

export const test = baseTestFixture(base, { collectCoverage: true });
export const expect = extendExpect(baseExpect);
```

Before each page closes, the fixture reads `window.__coverage__` and attaches it to the test report as
an Istanbul coverage JSON file, uploaded like other artifacts such as videos.

## Build the report

Download the coverage files for a test run, then build the report with `nyc`.

Fetch the run with the [Get a test run](https://empirical.run/docs/api-reference/test-runs/get-a-test-run.md) API and download
the Playwright JSON report from its `summary_url`. Replace `<TEST_RUN_ID>` with the run's ID:

```sh theme={null}
REPORT_URL=$(curl -s "https://api.empirical.run/api/test-runs/<TEST_RUN_ID>" \
  -H "Authorization: Bearer $EMPIRICALRUN_KEY" \
  | jq -r '.data.test_run.testRun.summary_url')

curl -sf -H "Authorization: Bearer $EMPIRICALRUN_KEY" "$REPORT_URL" -o report.json
```

Download every coverage file in the report into `.nyc_output`:

```sh theme={null}
mkdir -p .nyc_output
jq -r '
  [.suites[] | recurse(.suites[]?) | .specs[]? | .tests[]? | .results[]? | .attachments[]?
   | select(.contentType == "application/json" and (.name | test("coverage"))) | .path
  ] | .[]
' report.json | while read -r url; do
  curl -sf -H "Authorization: Bearer $EMPIRICALRUN_KEY" "$url" -o ".nyc_output/$(basename "$url")"
done
```

From your application source directory, build the HTML report:

```sh theme={null}
cd /path/to/your-app-code
npm install --save-dev nyc

npx nyc report --reporter=html \
  --temp-dir=/path/to/final-output-dir/.nyc_output \
  --report-dir=/path/to/final-output-dir
```

Open `/path/to/final-output-dir/index.html` to see coverage by file.

### Coverage per test

To see which test covered which file, map each test case ID to its coverage files:

```sh theme={null}
jq '
  [.suites[] | recurse(.suites[]?) | .specs[]? |
    {id: .id} + {
      coverage: [.tests[]? | .results[]? | .attachments[]?
        | select(.contentType == "application/json" and (.name | test("coverage")))
        | (.path | split("/") | last)
      ]
    }
  ] | map(select(.coverage | length > 0))
' report.json > coverage-map.json
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.