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.
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
:
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:
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:
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 : )