简体   繁体   中英

clean if mocha passes tests

I am trying to build a gulp based on a grunt file, what the grunt file does is activate a server, run mocha then close the server. If mocha passes all tests clean the log file. I look thru some gulp examples and found the .on('error') event. It's not really what I need because from what I can tell it only runs if mocha has an error. I need something like this:

gulp.task('mocha',['startServer'], function() {
return gulp.src('./js/test/actual/*.js', {read:false})
    .pipe(mocha({
        reporter: 'spec',
        ui : "tdd"
    }))
    .on('test fail', function () {//Check if all tests pased(aka. at least one test failed)
        //Do the clear here
    });

});

I found a solution:

var cleanUp = true;

function handleError(err) {
    cleanUp = false;
    console.log("Error detected in mocha(probably a test failed) :\n" +err.toString());
    this.emit('end');
}

We get a var to remember if we had errors or not and a callback function to deal with the error that gulp-mocha will throw in case there are failed tests(a try-catch block does not work from my experience probably doe to the asynchronous nature).

gulp.task('mocha', function() {
    run('forever start -o server.log -e server.log server.js').exec();
        return gulp.src('./js/test/actual/*.js', {read: false})
            .pipe(mocha({
                reporter: 'spec',
                ui: "tdd"
            }))
            .on("error",handleError);
});

Mocha will modify the cleanUp var if it detects an error.

gulp.task('default',['mocha'], function () {
    run('forever stop server.js').exec().on('error', handleError1);
    if (cleanUp) {
        console.log("Mocha successfully passed, deleting the log");
        fs.unlink("./server.log",  function(err){
            if (err) console.log("fs.unlink error:\n" + err.toString());
        });
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM