2

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?

Victor Savkin
  • 1,749
  • 1
  • 12
  • 17

1 Answers1

6

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
superjos
  • 12,189
  • 6
  • 89
  • 134
MarcoL
  • 9,829
  • 3
  • 37
  • 50