2

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 2

3

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.

-2

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.

4
  • I may have worded myself wrong, this is specifically for testing single files while doing Test Driven Development.
    – lpetrucci
    Nov 24, 2021 at 10:14
  • You can test a specific file by adding the test path to the command. jest -c path/to/config path/to/test Nov 30, 2021 at 3:49
  • Sorry but this just doesn't have anything to do with what I'm asking. I clearly already know all of this as the same command is in my OP.
    – lpetrucci
    Nov 30, 2021 at 11:42
  • If it doesn't have anything to do with what you're asking, then your question is poorly written. Use a config file to specify coverage reporters, then add a list of files you want to test. If that doesn't answer your question, you may want to reword what you've already posted. Dec 1, 2021 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.