【问题标题】:Detecting Environment When Running Karma运行 Karma 时检测环境
【发布时间】:2014-06-18 02:38:55
【问题描述】:

我有两个运行测试的环境(本地和 travic ci)。如果我在本地运行它们,我需要对我的测试进行一些调整。

是否可以在没有两个单独的配置文件的情况下使用 Karma 来做到这一点?

【问题讨论】:

  • 我会使用一个包装器来启动业力,并从这个包装器中根据位置更改配置。
  • 改配置是指选择配置文件吗?
  • 我的意思是您可以通过编程方式调用 karma 并将配置对象传递给它。我会写一个答案。

标签: karma-runner


【解决方案1】:

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

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

  if(exitCode){
    console.err('Error in somewhere!');
  }
});

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

想象一下在 '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'
    ]

  });
};

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

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');

目前使用这种技术,我们正在为我们的所有环境生成多个配置。

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

更新

如果您想将参数(例如配置文件路径)传递给脚本,则只需在参数数组中查找即可。

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

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

然后:

$ node startKarma.js ../path/to/karma.conf.js

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-11
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多