Hello React Vitest

React and Vitest

Code Coverage

Code coverage is a measure of how much of your code is being tested by your test suite.
It can help you identify which parts of your code are not being exercised by your tests, so that you can write additional tests to increase coverage.

2022-12-26
4 min read
Difficulty
react
typescript

In JavaScript, there are several tools that can measure code coverage, including Istanbul and Jest.

These tools can generate reports that show you which lines of code are being executed when your tests are run, and which lines are not. This can help you ensure that your tests are thorough and that your code is working as intended.

SOURCE: Chat GPT 😅

These tools show you what tests pass or fail but also the percentage of code you have tested for each component / script: lines, functions, branches and more.

Add following script to package.json:

JavaScript
package.json
  "coverage": "vitest run --coverage"

First time you run this command, it will ask to install the default Vitest coverage tool option coverage-c8. Press yes to confrm

Re-Run npm run coverage:

It will also generate an HTML site that you can open into a webserver:

and that's the result:

Install Istanbul

You can also select other coverage tools if you prefer or have experience with them, like the famous Istanbul, by setting it in the vite configuration file:

TypeScript
vite.config.ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import checker from 'vite-plugin-checker';

export default defineConfig({
  // NEW
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: './setupTests.ts',
    coverage: {
      provider: 'istanbul' // <==
    }
  },
  plugins: [
    react(),
    checker({ typescript: true }),
  ],
})

Re-Run npm run coverage and it will ask to install "istanbul":

That's all. I hope you enjoyed this tutorial : )

Keep updated about latest content
videos, articles, tips and news
BETA