运行Karma时检测环境

Vic*_*kin 2 karma-runner

我有两个环境,我正在运行我的测试(本地和travic ci).如果我在本地运行它,我需要在测试中做一些调整.

是否可以使用Karma而不使用两个单独的配置文件?

Mar*_*coL 6

您可以以编程方式调用karma并将其传递给配置对象,然后侦听回调以关闭服务器:

karma.server.start(config, function (exitCode){

  if(exitCode){
    console.err('Error in somewhere!');
  }
});
Run Code Online (Sandbox Code Playgroud)

配置对象基本上是一个包含一些属性的对象,您可以使用它来丰富您已有的骨架配置文件.

想象一下在'path/to/karma.conf.js'中有如下配置文件:

// Karma configuration

module.exports = function(config) {
  config.set({

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // frameworks to use
    frameworks: ['mocha'],

    files: [ ... ].

    // test results reporter to use
    // possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
    // choose it before starting Karma


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    browsers: ['PhantomJS'],

    // If browser does not capture in given timeout [ms], kill it
    captureTimeout: 60000,


    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: true,

    plugins: [
      'karma-mocha',
      'karma-phantomjs-launcher'
    ]

  });
};
Run Code Online (Sandbox Code Playgroud)

现在我想在开始业力之前调整一下:

function enrichConfig(path){
  var moreConfig = {
    // say you want to overwrite/choose the reporter
    reporters: ['progress'],
    // put here the path for your skeleton configuration file
    configFile: path
  };
  return moreConfig;
}

var config = enrichConfig('../path/to/karma.conf.js');
Run Code Online (Sandbox Code Playgroud)

目前,通过这种技术,我们为所有环境生成了多种配置.

我猜你可以配置你的TravisCI配置文件将一些参数传递给包装器,以激活enrichConfig函数中的某些特定属性.

更新

如果要将参数(例如配置文件路径)传递给脚本,则只需在arguments数组中查找以获取它.

假设您上面的脚本保存在startKarma.js文件中,将代码更改为:

 var args = process.argv;
 // the first two arguments are 'node' and 'startKarma.js'
 var pathToConfig = args[2];
 var config = enrichConfig(pathToConfig);
Run Code Online (Sandbox Code Playgroud)

然后:

$ node startKarma.js ../path/to/karma.conf.js
Run Code Online (Sandbox Code Playgroud)