Detecting Environment When Running Karma

天大地大妈咪最大 提交于 2019-12-17 17:07:22

问题


I have two environments I'm running my tests in (locally, and travic ci). And I need to make a few tweaks in my tests if I'm running them locally.

Is it possible to do it using Karma without having two separate configuration files?


回答1:


You can programmatically call karma and pass it a configuration object, then listen the callback to close the server:

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

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

The config object is basically an object that contains some properties and you can use it to enrich a skeleton configuration file you already have.

Imagine to have a configuration file like the following in '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'
    ]

  });
};

Now I want to tweak it a bit before starting karma:

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

Currently with this technique we're generating several configuration for all our environment.

I guess you can configure your TravisCI configuration file to pass some arguments to the wrapper in order to activate some particular property in the enrichConfig function.

Update

If you want to pass parameters (e.g. the configuration file path) to your script, then just look up in the arguments array to pick it up.

Assume your script above it saved in a startKarma.js file, change your code to this:

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

then:

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


来源:https://stackoverflow.com/questions/24276239/detecting-environment-when-running-karma

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!