Published on

Jest coverage report でプルリクエスト毎にコードカバレッジを可視化する

Authors

定期的にコードカバレッジを取得してチェックするのもよいのですが,気付いた頃にカバレッジが下がっていた…となっては遅いので,プルリクエスト単位でカバレッジを可視化して常に意識するようにしましょう。

※ GitHub + GitHub Actions を使用する前提です。

Codecov のようなカバレッジサービスを使用できるのであれば使いましょう。何かしらの理由で使えない場合の選択肢の 1 つが GitHub marketplace に公開されている Jest coverage report です。

https://github.com/marketplace/actions/jest-coverage-report
※ 2021-01 頃から開発が始まって 2021-08-09 現在,バージョンは v2.0-rc.3 で絶賛開発中です。

まだ README.md の更新が追いついていないようで,動作させるまでに結構ハマったのでエントリ化しておきます。


はじめに,実際に動いているもの,実装したものを貼っておきます。
https://github.com/oikwsat/jest-sample/pull/1#issuecomment-895044127

Jest-coverage-report PR comment

GitHub Action workflow です。
https://github.com/oikwsat/jest-sample/blob/main/.github/workflows/jest-coverage-report.yml


それでは早速ハマりどころを見ていきます。

1. Customizing test script の記述が古い

README.md にある Customizing test script の記述が更新されておらず,デフォルト値を参考に test-script を書いてしまうと動きません。

npx jest --silent --ci --coverage --coverageReporters="text" --coverageReporters="text-summary"

2. Use existing test report(s) が未実装

このオプションはまだ実装されていないようで動きません。

with:
    coverage-file: ./coverage/report.json
    base-coverage-file: ./coverage/master/report.json

この2つの問題があるため,次の方法で解決します。
package.json の script で --outputFile=\"report.json\" を指定し
workflow.yml の test-script で指定した script を指定します。
具体的には次のように書きます。

package.json

  "scripts": {
    "coverage:ci": "jest --coverage --silent --ci --testLocationInResults --json --outputFile=\"report.json\""
  },

workflow.yml

  uses: artiomtr/jest-coverage-report-action@v2.0-rc.3
    with:
      github-token: ${{ secrets.GITHUB_TOKEN }}
      package-manager: yarn
      test-script: yarn coverage:ci

この設定で回避することで,無事に PR に対してコードカバレッジがコメントされるようになりました。