how to write to file when using gulp and mocha?
Asked Answered
H

3

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);
});
Hustings answered 19/1, 2016 at 13:58 Comment(0)
W
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);
});
Wardell answered 20/1, 2016 at 16:46 Comment(2)
This also writes console.log prints to the JSON file, which render useless.. Do you have a workaround? Thanks!Danille
@GalMargalit Unfortunately no, this is a simple workaround to map the output into a file.Wardell
D
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

Danille answered 6/3, 2016 at 13:26 Comment(0)
A
1

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

.pipe(gulp.dest('./somewhere')); 
Archdeacon answered 6/3, 2016 at 21:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.