Gulp running Karma: getting rid of formatError in gulp.js

Gulp running Karma: getting rid of formatError in gulp.js

Did you ever run Karma inside a Gulp task? Then you perhaps have such a Gulp task setup:

gulp.task('karma:chrome', 'Unit tests with Karma in Chrome', function (cb) {
    new karma({
        configFile: 'karmaconf.json',
        browsers: ['Chrome']
    }, cb).start();
});

Unfortunately, with the current versions of Gulp 3.9.1 and Karma 0.13.22, having a red test in Karma yields the following formatError in Gulp, which is also documented here:

'karma:chrome' errored after 8 s
Error: 1
    at formatError (user\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:169:10)
    at Gulp.<anonymous> (user\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:195:15)
    at Gulp.emit (events.js:107:17)
    at Gulp.Orchestrator._emitTaskDone (project\node_modules\gulp\node_modules\orchestrator\index.js:264:8)
    at project\node_modules\gulp\node_modules\orchestrator\index.js:275:23
    at finish (project\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:21:8)
    at cb (project\node_modules\gulp\node_modules\orchestrator\lib\runTask.js:29:3)
    at removeAllListeners (project\node_modules\karma\lib\server.js:336:7)
    at Server.<anonymous> (project\node_modules\karma\lib\server.js:347:9)
    at Server.g (events.js:199:16)
    at Server.emit (events.js:129:20)
    at net.js:1409:10
    at process._tickCallback (node.js:355:11)

This happens due to the callback handling. Karma provides an integer error number to Gulp via the callback, unfortunately Gulp in the current version can’t handle integer numbers, but requires an Error object instead. What we can do now and what solves the problem is to provide a custom function, which creates an Error object from the Karma error code and calls the callback directly:

gulp.task('karma:chrome', 'Unit tests with Karma in Chrome', function (cb) {
    new karma({
        configFile: 'karmaconf.json',
        browsers: ['Chrome']
    }, function (err) { handleKarmaError(err, cb); }).start();
});

var handleKarmaError = function (error, callback) {
    if (error && typeof error !== 'Error') {
        error = new Error('Karma test run failed (error code: ' + error + ')');
        error.showStack = false;
    }

    callback(error);
}

Mission accomplished 🙂

Ich bin freiberuflicher Senior Full-Stack Web-Entwickler (Angular, TypeScript, C#/.NET) im Raum Frankfurt/Main. Mit Leidenschaft für Software-Design, Clean Code, moderne Technologien und agile Vorgehensmodelle.

0 Kommentare

Eine Antwort hinterlassen

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

*

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.