Jest: Automatically collect coverage from tested files

Viewed 1465

In my application, while developing, I run:

npm run test src/components/component.test.tsx

This runs the specific test suite for the component I'm working on. On top of that, I can then change it to:

npm run test src/components/component.test.tsx -- --coverage --coverageReporters=text-summary --collectCoverageFrom=src/components/component.tsx

Which will print a coverage report for that specific file once the tests have been run.

As you can see this is extremely wordy and only gets worse if I want to test two or three files at the same time.

Is there any way to automate collectCoverageFrom to collect coverage from the files that have been tested (not from all files in the project) so that I don't have to type it out manually every single time?

2 Answers

Just omit the "collectCoverageFrom" (or explicitly set it to an empty glob if you're overriding the config file).

Jest will then only collect coverage from files that are used during the test run.

Set it up in your jest configuration file.

your npm script will look like jest -c path/to/jest.config.js jest.config.js will look like

module.exports = {
  collectCoverage: true,
  // The directory where Jest should output its coverage files
  coverageDirectory: "./coverage",
  // Indicates which provider should be used to instrument code for coverage
  coverageProvider: "v8",
  // A list of reporter names that Jest uses when writing coverage reports
  coverageReporters: ["html", "text", "cobertura"],
}

If you do jest --init it will help you build a new config file

Side note: You may want to set up a jest wildcard so you don't need to individually write down every file you want to test.

Related