21
votes

I am running jest test with code coverage in GitLab CI and GitLab captures the percentage from stdout of a runner in gitlab.

jest --coverage produces the coverage in stdout and gitlab captures it using /All files[^|]*\|[^|]*\s+([\d\.]+)/ regexp but when I run jest --coverage --json --outputFile=xyz.json sadly jest doesn't print the code coverage to stdout.

What can I do to get code coverage in stdout from jest when --json arguments is given to jest?

jest version : v22.4.3 same for jest-cli

3

3 Answers

40
votes

The following configuration will let GitLab interpret the coverage report generated by Jest:

stages:
  - test

Unit tests:
  image: node:12.17.0
  stage: test
  script:
    - jest --coverage
  coverage: /All\sfiles.*?\s+(\d+.\d+)/

There's an open issue on GitLab which contains the correct regex for coverage reports generated using Jest (which is used by Create React App).

1
votes

I'm not familiar with Jest, but if you are creating a JSON the simplest way would be to simply cat the JSON then change the regex accordingly

1
votes

I'm using the following regex to parse the text-summary coverage reports from Jest for Gitlab: ^(?:Statements|Branches|Functions|Lines)\s*:\s*([^%]+)

Note that Gitlab will only consider the last match though. So above could be written as ^Lines\s*:\s*([^%]+). I included the full example so that you can choose the one that makes the most sense for your project.

The "text-summary" report looks like this in StdOut:

=============================== Coverage summary ===============================
Statements   : 80.49% ( 2611/3244 )
Branches     : 65.37% ( 923/1412 )
Functions    : 76.48% ( 582/761 )
Lines        : 80.44% ( 2583/3211 )
================================================================================

Make sure you have included text-summary as a coverage reporter in your jest.config.js:

coverageReporters: ['text-summary', 'lcov', 'cobertura'],