Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write to file when using gulp and mocha?

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);
});
like image 881
Bala Avatar asked Jan 19 '16 13:01

Bala


3 Answers

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);
});
like image 91
vorillaz Avatar answered Nov 04 '22 14:11

vorillaz


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

like image 22
Gal Margalit Avatar answered Nov 04 '22 12:11

Gal Margalit


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

.pipe(gulp.dest('./somewhere')); 
like image 32
Tomáš Fejfar Avatar answered Nov 04 '22 12:11

Tomáš Fejfar