11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.jsでテストのカバレッジを取る

Posted at

サンプル
https://github.com/iwata-n/nodejs_coverage

node.js+expressで作ってるプロジェクトのテストでカバレッジを取りたかったので調べてみた結果をまとめておく。

gulp

ビルドツールとしてgulpを使う。gruntも有るっぽいけどもgulpを使う。

カバレッジ取得ツール

istanbulを使う。istanbulをgulpのプラグインとして用意してくれている人がいるので感謝

設定

gulp-istanbulのREADMEに従ってgulpfile.jsを用意する。
express-generatorが出してきたままなコードになっている。

var gulp = require('gulp');
var istanbul = require('gulp-istanbul');
var mocha = require('gulp-mocha');

gulp.task('pre-test', function () {
  return gulp.src(['routes/*.js'])
    // Covering files
    .pipe(istanbul())
    // Force `require` to return covered files
    .pipe(istanbul.hookRequire());
});

gulp.task('test', ['pre-test'], function () {
  return gulp.src(['test/*.js'])
    .pipe(mocha())
    // Creating the reports after tests ran
    .pipe(istanbul.writeReports())
    // Enforce a coverage of at least 90%
    .pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } }));
});

実行

gulp test で実行される。
こんな感じでカバレッジの結果が表示される。

$ gulp test
[16:53:47] Using gulpfile ~/hoge/gulpfile.js
[16:53:47] Starting 'pre-test'...
[16:53:47] Finished 'pre-test' after 50 ms
[16:53:47] Starting 'test'...


  GET /users
GET /users 200 7.133 ms - 8
    ✓ no param (40ms)


  1 passing (45ms)

-----------|----------|----------|----------|----------|----------------|
File       |  % Stmts | % Branch |  % Funcs |  % Lines |Uncovered Lines |
-----------|----------|----------|----------|----------|----------------|
 routes/   |    76.92 |       50 |       50 |    76.92 |                |
  index.js |       80 |      100 |        0 |       80 |              6 |
  users.js |       75 |       50 |      100 |       75 |            7,8 |
-----------|----------|----------|----------|----------|----------------|
All files  |    76.92 |       50 |       50 |    76.92 |                |
-----------|----------|----------|----------|----------|----------------|


=============================== Coverage summary ===============================
Statements   : 76.92% ( 10/13 )
Branches     : 50% ( 1/2 )
Functions    : 50% ( 1/2 )
Lines        : 76.92% ( 10/13 )
================================================================================
[16:53:47] 'test' errored after 336 ms
[16:53:47] Error in plugin 'gulp-istanbul'
11
8
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
11
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?