Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract test coverage from the istanbul text-summary reporter with a regex?

Gitlab CI requires you to specify a regex to extract the statements code coverage (so that they can display it). Given the build output below (with jest and istanbul), I've managed to come as far as: /Statements.*(\d+\%)/

... (other build output)
=============================== Coverage summary ===============================
Statements   : 53.07% ( 95/179 )
Branches     : 66.67% ( 28/42 )
Functions    : 30.99% ( 22/71 )
Lines        : 50.96% ( 80/157 )
================================================================================
... (other build output)

This highlights the part Statements : 53.07% (see here: http://regexr.com/3e9sl). However, I need to match only the 53.07 part, how do I do that?

like image 931
vkjb38sjhbv98h4jgvx98hah3fef Avatar asked Sep 23 '16 10:09

vkjb38sjhbv98h4jgvx98hah3fef


People also ask

How is code coverage used in Istanbul?

Under the hood, this script is using Jest to run all of the tests in the new app. Conveniently for you, Istanbul can be used to provide a coverage report by simply adding the --coverage flag onto the end of the test command like this: react-scripts test --coverage .

How do you read a jest coverage report?

Understanding the code coverage report This command will generate an HTML report in the folder you specified with --coverageDirectory . If you open up the index. html file in your browser, you will see lines highlighted in red. These are the lines that are not currently covered by your unit tests.


1 Answers

I need to match only the 53.07 part,

Use lazy .*?, add (?:\.\d+)? to also match floats, and access the capture group:

var re = /Statements.*?(\d+(?:\.\d+)?)%/; 
var str = '... (other build output)\n=============================== Coverage summary ===============================\nStatements   : 53.07% ( 95/179 )\nBranches     : 66.67% ( 28/42 )\nFunctions    : 30.99% ( 22/71 )\nLines        : 50.96% ( 80/157 )\n================================================================================\n... (other build output)';
var res = (m = re.exec(str)) ? m[1] : "";
console.log(res);

Note that Statements.*?(\d+(?:\.\d+)?)% also allows integer values, not only floats.

Pattern description:

  • Statements - a literal string
  • .*? - zero or more chars other than whitespace, but as few as possible
  • (\d+(?:\.\d+)?) - Group 1 (the value you need will be captured into this group) capturing 1+ digits and an optional sequence of . and 1+ digits after it
  • % - a percentage sign (if you need to print it, move it inside parentheses above)

See the regex demo.

like image 145
Wiktor Stribiżew Avatar answered Sep 23 '22 21:09

Wiktor Stribiżew