<aside> ℹ️

Storybook Test has launched and the full documentation is available here: https://storybook.js.org/docs/writing-tests

</aside>

Test coverage is the practice of measuring whether existing tests fully cover your code. It marks which conditions, logic branches, functions and variables in your code are and are not being tested.

Coverage tests examine the instrumented code against a set of industry-accepted best practices. They act as the last line of QA to improve the quality of your test suite.

Each project’s coverage report will look different, but the important things to note are:

  1. The overall line/branch coverage, which serves as a high-level health check.
  2. Specific lines/branches that are not covered, which are potential test gaps.

When you run component tests with the Test addon, which is powered by Vitest, it can generate a coverage report. The result is summarized in the testing module, showing the percentage of statements covered by your tested stories.

image.png

Set up

Coverage is included in the Test addon and, when enabled, will be calculated when running component tests for your project. To enable coverage, press the edit button (pencil icon) in the testing module and toggle coverage on:

image.png

Before coverage can be calculated, you may need to install a support package corresponding to your coverage provider:

# For v8
npm install --save-dev @vitest/coverage-v8
 
# For istanbul
npm install --save-dev @vitest/coverage-istanbul

Additionally, if you’re using a Vitest version before 3.0, the generated coverage report will include the stories files themselves and output from your built Storybook application. This is misleading and they should be excluded. To do this, you can add the following to your Vitest config:

// vitest.config.ts
import { coverageConfigDefaults, defineConfig } from 'vitest/config';
 
export default defineConfig({
  // ...
  test: {
    coverage: {
      // 👇 Add this
      exclude: [
         ...coverageConfigDefaults.exclude,
         '**/.storybook/**',
         // 👇 This pattern must align with the `stories` property of your `.storybook/main.ts` config
         '**/*.stories.*',
         // 👇 This pattern must align with the output directory of `storybook build`
         '**/storybook-static/**',
       ], 
    }
  }
})

Usage

Because coverage is built into the Test addon, you can use it everywhere you run your tests.

Storybook UI

When you enable coverage in the Storybook UI, the coverage report will be generated and summarized in the testing module after you run your tests. You can see the percentage of statements covered by your tested stories, as well as whether the coverage meets the watermarks.