LoginSignup
2
0

Github の Readme に Coverage badge を付ける

Last updated at Posted at 2022-11-22
更新履歴
  • 2023/07/23 nyc 関係を更新

目的

  • github の ReadMe に coverage badge を表示したい

前提

  • Node.jsの環境構築済み
  • GitGithubの環境構築済み

環境

  • Windows - v11
  • Node.js - v16
  • nyc - v15
  • mocha - v10
  • chai - v4
  • Coveralls - v3
  • Github Actions

結論

こうする。

package.json
}
  "scripts": {
    "pretest": "rm -rf .nyc_output",
    "test": "nyc mocha -R spec",
    "precoverage": "rm -rf coverage && mkdir coverage",
    "coverage": "npm run test && nyc report --reporter=lcovonly"
  },
  "devDependencies": {
    "chai": "^4.3.7",
    "coveralls": "^3.1.1",
    "mocha": "^10.1.0",
    "nyc": "^15.1.0"
  }
}
.nycrc
{
  "reporter": [
    "text-summary"
  ],
  "extension": [
    ".js",
    ".cjs",
    ".mjs",
    ".ts"
  ],
  "exclude": [
    "**/test/**.spec.js"
  ]
}
.github/workflow/coverage-badge.yml
name: Coveralls GitHub Action

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  workflow_dispatch:

jobs:
  test:
    runs-on: windows-latest

    strategy:
      matrix:
        node-version: [15.x, 16.x] # (need)

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }} # (need)
          cache: "npm"
          cache-dependency-path: "**/package-lock.json"

      - run: npm ci # (need) # better than "npm install"
      - run: npm run coverage # (need)

      - name: Coveralls GitHub Action
        uses: coverallsapp/github-action@1.1.3 # (need)
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }} # (need)
README.md
[![Coverage Status](https://coveralls.io/repos/github/[user]/coverage-badge-test/badge.svg?branch=main)](https://coveralls.io/github/[user]/coverage-badge-test?branch=main)

・・・ 以下 REAMDE 本文 ・・・

詳細

  • Test runner : mocha (NPM)
  • assertion library : Chai (NPM)
  • coverage tool : nyc (NPM)
  • coverage badge : coveralls (NPM)

1. nyc + mocha + chai のセットアップ

1.1. install

gitbash
$ npm install mocha --save-dev
$ npm install chai --save-dev
$ npm install nyc --save-dev

1.2. テスト対象の実行ファイルを作成

内容は適当。

index.js
module.exports = () => {
  console.log("Hallow World");
};

1.3. テストスクリプトの作成

デフォルトのファイル構成

  • :open_file_folder: test
    • :pencil: index.spec.js

内容は適当に。

test/index.spec.js
const { describe, it } = require("mocha");
const { assert } = require("chai");

describe("test index", () => {
  const index = require("../index");

  it("index is function", () => {
    assert.isFunction(index);
  });
});

1.4. npm run script を作成

以下の様にnycを噛ませてcoverageが出力される様にする。

package.json
{
  "scripts":{
    "test": "nyc mocha -R spec"
  }
}

1.4. テストの実行確認

スクリプトを実行

gitbash
$ npm run test

以下の様にcoverageが表示されれば、一旦OK

gitbash
> nyc mocha -R spec

  test index
    ✔ index is function

  1 passing (6ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |      50 |      100 |       0 |      50 |
 index.js |      50 |      100 |       0 |      50 | 2
----------|---------|----------|---------|---------|-------------------

情報
nyccoverageを出力すると、以下の様に.nyc_outputディレクトリが自動生成されますが、coverageの生データであり、気にする必要はありません。(temp-dir:"./.nyc_output"(参考:github))

  • :open_file_folder: .nyc_output

2. Coverallsをセットアップ

2.1. coveralls.ioにアカウントを作成する

リンク:Coveralls.io

  • 公開リポジトリ+OSSであれば、無料。

2.2. coveralls.ioGithubを連携する

Coveralls.ioからGithubにHTTPリクエストが発生するので、その認証が必要。らしい。

連携が出来ていれば、coveralls.ioアカウントページGithubのプロフィールアイコンが表示される。ハズ。

image.png

2.3. Coveralls.ioGithubの各リポジトリを紐づけする

このページに行くと、Githubの個人リポジトリの一覧が表示されるので、

image.png

coverage-badgeを出力したいリポジトリ(今いじっているリポジトリ)を OFF → ON に切り替える。まだリモートリポジトリを作って無いのならこのタイミングGithubに作成しちゃいましょう。

image.png

2.4. install

gitbash
$ npm install --save-dev coveralls

2.5. npm run script を作成する

coverallsが読み込み可能なcoverage-reportが出力される様にする必要がある。

package.json
{
  "scripts":{
    "test": "nyc mocha -R spec",
+   "precoverage": "rm -rf coverage && mkdir coverage",
+   "coverage": "npm run test && nyc report --reporter=lcovonly"
  }
}

解説

  • coverage-reportcoverallsの仕様上./coverage/lcov.infoファイルにtext-lcov形式で出力される必要がある。ファイルパスが一致しない場合はError: Lcov file not found.を出力して終了する。
  • nycreporterはファイル形式、出力ディレクトリの指定はできるが、ファイル名の指定が出来ない。また、出力場所を指定したとしてもそのディレクトリが無い場合、エラーを出力して終了する。
  • 上記の理由から、まず出力場所である./coverageディレクトリを作成する必要がある。rm -rf coverage && mkdir coverage
    • MakeFileでやれ的な説明が多いが、コマンドラインから直接作っても動作した
  • node-coverallsgithubにはnyc npm test && nyc report --reporter=text-lcov | coverallsと書かれているが、それだと"Error : Failed to parse stringが出力され終了してしまう。
gitbash
[error] "2022-11-22T09:33:14.585Z"  'error from lcovParse: ' 'Failed to parse string'
[error] "2022-11-22T09:33:14.588Z"  'input: ' ''
[error] "2022-11-22T09:33:14.588Z"  'error from convertLcovToCoveralls'

C:\Users\[user]\workSpace\coverage-badge-test\node_modules\coveralls\bin\coveralls.js:19
      throw err;
      ^
Failed to parse string
(Use `node --trace-uncaught ...` to show where the exception was thrown)
  • なので、npm scriptではreporterの出力までを行い、あとはgithub-actionsに任せるのが良い。

2.6. reporterの実行確認

以下を実行

gitbash
$ npm run coverage-reporter

以下の様になればOK。

gitbash
> rm -rf coverage && mkdir coverage

> npm run test && nyc report --reporter=lcovonly

> rm -rf .nyc_output

> nyc mocha -R spec

  test index
    ✔ index is function

  1 passing (6ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |      50 |      100 |       0 |      50 |
 index.js |      50 |      100 |       0 |      50 | 2
----------|---------|----------|---------|---------|-------------------

確認
./coverage/lcov.infoファイルが作成されているか確認する。

  • :open_file_folder: coverage
    • :pencil: lcov.info
lcov.info
TN:
SF:index.js
FN:1,(anonymous_0)
FNF:1
FNH:0
FNDA:0,(anonymous_0)
DA:1,1
DA:2,0
LF:2
LH:1
BRF:0
BRH:0
end_of_record

3. Github Actionsを作成する

本ページ内の結論に書いた.github/workflow/coverage-badge.yml

3.1. Github Actionを実行

Githubのリモートリポジトリに今いじっているローカルリポジトリをpushして確認。

  1. リポジトリ内の上部にある「Actions」を押下
    image.png

  2. Actionisページ内の左部にある「Coveralls Github Action」を押下
    image.png

  3. ページ右部の「Run workflow▼」→「Run Workflow」を押下
    image.png

  4. 経過ログも見れるし、終了した後でもそのログを参照可能
    image.png

4. README にバッジを埋め込む

本ページ内の結論に書いたREADME.md

READMEに貼り付けるMarkdownは、coveralls.ioREPOSのページ内にあるBUILD #***のリンクを踏んだ先にある各ビルド毎のcoverage詳細ページにある「EMBED▼」ボタンからジェネレートできる。
image.png
image.png

こんな感じになればOK
image.png

参考リンク

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0