javascriptkarma-runnergulp-karma

Run karma test from JS without a config file


Is there any way I can run karma without specifying a static config file but giving it a configuration object instead?

The ideal scenario would look something like:

const karmaConfig = {...};

gulp.task('test', function (done) {
  new Server({
    config: karmaConfig,
    singleRun: true
  }, done).start();
});

Is there any way of doing that?

The reason behind it is that I want to have different test runs tackling different files, which I am specifying in a general configuration file somewhere else.


Solution

  • The solution I found is to use a temporary configuration file. The code goes like this:

    const tmp = require('tmp');
    const fs = require('fs');
    const gulp = require('gulp');
    
    function createConfigFileContent(configurationObject) {
      return `
      module.exports = function karmaConfig(config) {
        const conf = ${JSON.stringify(configurationObject)};
        conf.logLevel = config.LOG_INFO;
    
        return config.set(conf);
      };
      `;
    }
    
    function createConfigObject(testFiles) {
      const files = testFiles.map(f => ({ pattern: f, included: true }));
    
      return {
        basePath: process.cwd(), // project root
        frameworks: ['jasmine'],
        files,
        exclude: [],
        preprocessors: {},
        reporters: ['progress'],
        port: 9876,
        colors: true,
        autoWatch: false,
        browsers: ['Chrome'],
        singleRun: true,
        concurrency: Infinity,
      };
    }
    
    function generateConfig(runner, testFiles) {
      const config = createConfigObject(runner, testFiles);
    
      return createConfigFileContent(config);
    }
    
    
    gulp.task('karma', done => {
      // Create temporary configuration file
      const config = tmp.fileSync();
    
      // Populate it with config to run our files
      fs.writeFileSync(config.name, generateConfig(FILESARRAY));
    
      // Run karma
      return new KarmaServer({
          configFile: config.name,
          singleRun: true,
        },
        function cleanUp() {
          // Erase temporary config and finish task
          config.removeCallback();
          done();
        }).start();
    });