javascript 捕获 gulp-mocha 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21602332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Catching gulp-mocha errors
提问by Roy Jacobs
I may be missing something extremely obvious but I can't get gulp-mocha
to catch errors, causing my gulp watch
task to end everytime I have a failing test.
我可能遗漏了一些非常明显的东西,但我无法gulp-mocha
捕捉错误,导致gulp watch
每次测试失败时我的任务都会结束。
It's a very simple set up:
这是一个非常简单的设置:
gulp.task("watch", ["build"], function () {
gulp.watch([paths.scripts, paths.tests], ["test"]);
});
gulp.task("test", function() {
return gulp.src(paths.tests)
.pipe(mocha({ reporter: "spec" }).on("error", gutil.log));
});
Alternatively, putting the handler on the entire stream also gives the same problem:
或者,将处理程序放在整个流上也会出现同样的问题:
gulp.task("test", function() {
return gulp.src(paths.tests)
.pipe(mocha({ reporter: "spec" }))
.on("error", gutil.log);
});
I've also tried using plumber
, combine
and gulp-batch
to no avail, so I guess I'm overlooking something trivial.
我已经使用也试过plumber
,combine
并gulp-batch
没有用,所以我想我俯瞰一些小事。
回答by Shuhei Kagawa
You need to ignore 'error' and always emit 'end' to make 'gulp.watch' work.
您需要忽略 'error' 并始终发出 'end' 以使 'gulp.watch' 工作。
function handleError(err) {
console.log(err.toString());
this.emit('end');
}
gulp.task("test", function() {
return gulp.src(paths.tests)
.pipe(mocha({ reporter: "spec" })
.on("error", handleError));
});
This makes 'gulp test' to always return '0' which is problematic for Continuous Integration, but I think we have no choice at this time.
这使得 'gulp test' 总是返回 '0',这对于持续集成来说是有问题的,但我认为我们此时别无选择。
回答by abovethewater
Expanding on Shuhei Kagawa's answer..
扩展香川修平的回答..
emitting end will prevent gulp exiting due to the uncaught error being converted into an exception.
由于未捕获的错误被转换为异常,发射端将阻止 gulp 退出。
Set a watching var to track whether you are running test through watch, then exit or not depending on whether you are developing or running CI.
设置一个监视变量来跟踪您是否正在通过监视运行测试,然后根据您是在开发还是运行 CI 来退出与否。
var watching = false;
function onError(err) {
console.log(err.toString());
if (watching) {
this.emit('end');
} else {
// if you want to be really specific
process.exit(1);
}
}
gulp.task("test", function() {
return gulp.src(paths.tests)
.pipe(mocha({ reporter: "spec" }).on("error", onError));
});
gulp.task("watch", ["build"], function () {
watching = true;
gulp.watch([paths.tests], ["test"]);
});
This can then be used for development and CI
然后可以将其用于开发和 CI