Jasmine - 使用自定义报告器

时间:2015-09-06 12:16:39

标签: javascript jasmine gulp gulp-jasmine

我正通过Jasmine使用Gulp测试一些JavaScript。我想创建自己的记者。在这个时候,我的记者是基本的。它看起来像这样:

'use strict';

var myCustomReporter = {
    jasmineStarted: function(suiteInfo) {
        console.log('Running suite with ' + suiteInfo.totalSpecsDefined);
        console.log('Reporting via MyCustomReporter');      
    },

    suiteStarted: function(result) {
        console.log('Suite started: ' + result.description + ' whose full description is: ' + result.fullName);     
    },

    specStarted: function(result) {
        console.log('Spec started: ' + result.description + ' whose full description is: ' + result.fullName);
    },

    specDone: function(result) {
    },

    suiteDone: function(result) {
    },

    jasmineDone: function() {
        console.log('Finished suite');
    }   
};

上面的代码基本上是Jasmine提供的example custom reporter。我的挑战是,我无法弄清楚如何让Jasmine实际使用它。一些如何,我正在添加错误。我正在添加它:

 gulp.task('test', function() {
    // Load the reporters to use with Jasmine
    var myReporter = require('./reporters/myCustomReporter');   
    var reporters = [
        myReporter
    ];

    return gulp.src(input.tests)
        .pipe(jasmine({ reporter: reporters }))
    ;
 });

当我通过Gulp执行test任务时,我得到以下输出:

[08:04:15] Using gulpfile ~/MyProject/gulpfile.js
[08:04:15] Starting 'test'...
[08:04:20] 'test' errored after 5.25 s
[08:04:20] Error in plugin 'gulp-jasmine'
Message:
    Tests failed

如果我在调用Jasmine时没有传递{ reporter: reporters },我的测试运行得很好。我正在努力学习如何a)添加我的记者和b)仍然使用默认的记者。基本上,我正在试图弄清楚如何将结果发送给多个记者。我认为我的方法是正确的。显然,结果显示我错了。

1 个答案:

答案 0 :(得分:4)

首先确保您导出自定义报告者,如module.exports = myCustomReporter;

根据gulp-jasmine的来源,默认记者不会暴露。相关代码:

var Reporter = require('jasmine-terminal-reporter');
...
module.exports = function(options) {
  ...
  var color = process.argv.indexOf('--no-color') === -1;
  var reporter = options.reporter;

  if (reporter) {
    (Array.isArray(reporter) ? reporter : [reporter]).forEach(function (el) {
      jasmine.addReporter(el);
    });
  } else {
    jasmine.addReporter(new Reporter({
      isVerbose: options.verbose,
      showColors: color,
      includeStackTrace: options.includeStackTrace
    }));
  }
  ...
};

所以你可以像这样添加默认的记者:

gulp.task('test', function() {
    // Load the reporters to use with Jasmine
    var myReporter = require('./reporters/myCustomReporter');   

    var Reporter = require('jasmine-terminal-reporter');
    var defaultReporter = new Reporter({
      isVerbose: false,
      showColors: true,
      includeStackTrace: false
    });

    var reporters = [
        defaultReporter,
        myReporter
    ];

    return gulp.src(input.tests)
        .pipe(jasmine({ reporter: reporters }))
    ;
});