6

I have a sample gulp task that uses Mocha json reporter. I would like to write that json output to a file. Would appreciate some inputs.

Here is my code:

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

gulp.task('myreport', function() {
    return gulp.src(['tests.js'], { read: false })
        .pipe(mocha({ reporter: 'json' }))  //how do I write this to a file?
        .on('error', util.log);
});
Gal Margalit
  • 5,525
  • 6
  • 52
  • 56
Bala
  • 11,068
  • 19
  • 67
  • 120

3 Answers3

3

I have made it work looking at the source code. It seems that gulp-mocha does not follow the gulp pipeline to push it's outsource. You may use process.stdout.write though temporary mapping the outcome during the execution of the task.

Here is a simple example.

  var gulp = require('gulp'),
  mocha = require('gulp-mocha'),
  gutil = require('gulp-util'),
  fs = require('fs');

gulp.task('test', function () {
  //pipe process.stdout.write during the process
  fs.writeFileSync('./test.json', '');
  process.stdout.write = function( chunk ){
    fs.appendFile( './test.json', chunk );
  };

  return gulp.src(['hello/a.js'], { read: false })
      .pipe(mocha({ reporter: 'json' }))
      .on('error', gutil.log);
});
vorillaz
  • 6,098
  • 2
  • 30
  • 46
2

Use mochawesome reporter, you'll get JSON output and much more: https://www.npmjs.com/package/mochawesome

Another advantage of using this reporter is that you won't break your JSON writing stream on console.log messages etc.

.pipe(mocha({reporter: 'mochawesome'}))

mochawesome screenshot

Gal Margalit
  • 5,525
  • 6
  • 52
  • 56
1

Can't you just pipe it to gulp.dest?

.pipe(gulp.dest('./somewhere')); 
Tomáš Fejfar
  • 11,129
  • 8
  • 54
  • 82