How to get jest coverage only for changed files?
Asked Answered
B

1

25

I could not find my requirement for coverage in the jest docs. I have tried the following options but could not find the required solution to get jest coverage only for changed code.

npm test -- --coverage --onlyChanged This runs only changed tests but shows coverage for full suite.

npm test -- --coverage --changedSince=base-branch This runs all tests and shows coverage for full suite.

Found this discussion and it seems this issue is fixed. I am not sure why this is not working though?

Belle answered 27/11, 2019 at 6:28 Comment(5)
Were you able to figure it out? Since I am working with some legacy codebase I cannot just put some thresholds for the entire project. Rather I was planning to put a threshold on just the new code which is being checked in. For this I need to know the coverage for only the files which were changed.Terrorism
@PulkitGupta you found any solution?Diarchy
question is old, but I have made a script for the project I am working with to run coverage for just the current branch. It will most likely NOT work for you out of the bat, but it could help if you want to fiddle with some shell script, here is the link: gist.github.com/vhoyer/1a6a7ccc1e901cb0cba269017311ec39Commonalty
The fix in that discussion was released as part of jest v27.0.4 (if I'm reading it right). What version of jest are you using?Edlun
@Diarchy I think now jest supports this out of the box. Please check my answer for more details. I am using this with jest v24.9.0.Terrorism
T
19

Jest supports this out of the box.

jest --coverage --changedSince=master --coverageThreshold='{"global":{"statements":"50","branches":"50","functions":"50","lines":"50"}}'

The above command will only calculate the coverage for the code which was changed as compared to your master branch.

For this changed code you can also set the threshold coverage.

Terrorism answered 24/7, 2021 at 13:36 Comment(4)
Did not work for me. It still is running all the testsGrotto
Can you please check if your branches have diverged since it will then behave differently in that case.Terrorism
You can read more at: jestjs.io/docs/cli#--changedsinceTerrorism
Coming late to this, but @etotientz, why do you expect it to not RUN all of the tests? The command runs all the tests because you didn't filter it. It should report coverage only on files that have changed though. I suppose you could use git to determine which files have changed and explode those out to a list of specs for jest to run...Bacchant

© 2022 - 2024 — McMap. All rights reserved.