Skip to content

Instantly share code, notes, and snippets.

@beresmate
Last active May 12, 2016 18:17
Show Gist options
  • Save beresmate/7932473 to your computer and use it in GitHub Desktop.
Save beresmate/7932473 to your computer and use it in GitHub Desktop.
Run mocha processes parallel from a Grunt task.
module.exports = function (grunt) {
// collect the test files from our test folder
// for example grunt.file.expand
function getTests () {
var tests = [
{
filePath: '/Users/Mate/Desktop/LoginTest.js',
name: 'Login test'
},
{
filePath: '/Users/Mate/Desktop/LogoutTest.js',
name: 'Logout test'
}
];
return tests;
}
// create and return a function which starts the mocha child process
function createTestRunner (test) {
var capabilites = {
browserName: 'firefox'
};
// this function will be executed by async.parallel in the grunt task
return function (callback) {
acuireSession(capabilities, function (err, sessionId) {
// start the Mocha process after we got the browser running
// and inject the sessionId ad an environment variable
grunt.util.spawn({
cmd: 'mocha',
args: [test.filePath, '-R', 'json'],
opts: {
env: _.extend({}, process.env, {
sessionId: sessionId,
testName: test.name
})
}
}, function (err, res) {
// do something with res.stdout
// which will contain Mocha's json output
callback(err, res.stdOut);
});
});
}
}
// get a test session for a specific browser and os type
// (this will start a new browser on the selenium node)
function acuireSession (capabilities, callback) {
request({
uri: 'http://localhost:4444/wh/hub/session',
method: 'POST',
headers: { 'content-type' : 'application/json;charset=UTF-8' },
body: {
JSON.stringify({ desiredCapabilities: capabilities })
}
}, function (err, response) {
callback(err, response.sessionId)
});
}
// register our grunt task, named 'selenium'
grunt.registerTask('selenium', function () {
var done = this.async(),
// this will contain the list of test definitions (path to file, name, etc)
tests = getTests(),
// this will contain an array of executable test functions
testRunners = _.map(tests, createTestRunner);
// start all the tests at the same time
async.parallel(testRunners, function (err, results) {
// do something with aggregated Mocha results
_.each(results, function (result) {
console.log(result.stats.passed, result.stats.failed);
});
// let Grunt know our task is finished
done();
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment