VladosJS
VladosJS

Reputation: 538

How to run unit tests by chunks in karma-webpack?

We are using following technologies in our project:

angularjs+typescript+webpack+karma+phantomjs

We have more than 1000 unit tests in the project which are run bu karma-phantomjs-launcher and on windows machines phantoms crashes with the following exception:

[phantomjs.launcher]: Fatal Windows exception, code 0xc0000005.

Is it possible to split tests to chunks and run them one chunk by another?

Upvotes: 0

Views: 685

Answers (1)

VladosJS
VladosJS

Reputation: 538

Solution is the following: custom-karma.js

const Server = require('karma').Server;
const filesFromJson = require('./karma.files.json');
const glob = require("glob");
const cfg = require('karma/lib/config');
const _ = require("lodash");
const path = require("path");
const minConfig = require('./karma.min.js');
const EventEmitter = require('events');
class ChunkEmitter extends EventEmitter {}
const chunkEmitter = new ChunkEmitter();

// register karma server and setup listener.
const registerKarmaServerAndSetListeners = (config, chunkNumber) => {
    const server = new Server(
        config,
        () => {
          console.log('test suite are done' + chunkNumber);
          // when first chunk of tests is done we have to call another chunk
          const nextChunk = ++chunkNumber;
          console.log('proceeding  ' + nextChunk);
          chunkEmitter.emit('chunk' + nextChunk);
        }
    );
    // listening for server starting event and starting server.
    chunkEmitter.on('chunk' + chunkNumber, ()=> {
        console.log('staring ' + chunkNumber);
        server.start();
    });
}
const readAllSpecsSplitIntoChunksEmitServer = () => {
    glob("src/**/*spec.ts", {}, (er, files) => {
        // spliting all specs into chunks. 
        const chunkedFiles = _.chunk(files, 50);
        chunkedFiles.forEach((chunk, index) => {
            let chunkedFiles = filesFromJson.coreFiles.concat(chunk);
            let karmaConfig = cfg.parseConfig(path.resolve('./karma.config.js'), {
                files: chunkedFiles
            });
            registerKarmaServerAndSetListeners(karmaConfig, index);
        });
        // starting tests from chunk0
        chunkEmitter.emit('chunk0');
    })
}

readAllSpecsSplitIntoChunksEmitServer();

in order to run it just run following: node custom-karma.js

Upvotes: 0

Related Questions