Codementor Events

How to show test coverage using Gulp as a task runner and mocha

Published Feb 27, 2018
How to show test coverage using  Gulp as a task runner and mocha

Having tried webpack and I love it, I wanted to use a taskrunner to compile my es6 code to es5 using babel as the transpiler and gulp as the taskrunner. Yes I did it Hurray! it worked but I got a blocker when I started writing tests for my api. Test coverage refused to show after doing lots of tweaking. After going through the web, I couldn't find a solution so I resorted to solving it myself after getting pieces from the web.

Below is a guide on how I did it.

In your gulpfile

import dependencies

import gulp from 'gulp';
import loadPlugins from 'gulp-load-plugins';
import path from 'path';
import shell from 'gulp-shell';

// Load the gulp plugins into the plugins variable

const plugins = loadPlugins();

// Compile all Babel Javascript into ES5 and place in dist folder

const paths = {
  js: ['./**/*.js', '!dist/**', '!node_modules/**', 
  '!./server/tests/**']
};

// Compile all Babel Javascript into ES5 and put it into the dist dir

gulp.task('babel', () =>
  gulp.src(paths.js, { base: '.' })
    .pipe(plugins.babel())
    .pipe(gulp.dest('dist'))
);

//this is for relational database for migration if it is required

gulp.task('migrate', shell.task([
  'cross-env NODE_ENV=test sequelize db:migrate',
]));

This is where the coverage happen with nyc. This tells nyc to show all coverage in the test directory after mocha has run all test in the directory

gulp.task('coverage', shell.task([
  'cross-env NODE_ENV=test nyc mocha ./server/test/**/*.js',
]));

// Restart server with on every changes made to file

gulp.task('nodemon', ['babel'], () =>
  plugins.nodemon({
    script: path.join('dist', 'index.js'),
    ignore: ['README.md', 'node_modules/**/*.js', 'dist/**/*.js'],
    ext: 'js',
    tasks: ['babel']
  })
);

gulp.task('test', ['migrate', 'coverage']);
gulp.task('default', ['nodemon']);
gulp.task('production', ['babel']);

We are not done yet, When you run your test, you will find out your coverage is just showing percentage without the test files.

Next is to go into your package.json and add ...

"nyc": {
    "require": [
      "babel-register"
    ],
    "reporter": [
      "lcov",
      "text",
      "html"
    ],
    "sourceMap": false,
    "instrument": false,
    "exclude": [
      "the test file you want to exclude from coverage"
    ]
  }

Yeah! We did it. Lets celebrate

Don't forget to like. Feel free to follow me on twitter

Discover and read more posts from Akhator Itua
get started