Skip to content

Instantly share code, notes, and snippets.

@tcoopman
Created March 20, 2015 22:18
Show Gist options
  • Save tcoopman/243104e5df8cd99467c7 to your computer and use it in GitHub Desktop.
Save tcoopman/243104e5df8cd99467c7 to your computer and use it in GitHub Desktop.
Gulp, webpack and mocha tester
var gulp = require('gulp');
var webpack = require('webpack');
var path = require('path');
var fs = require('fs');
var DeepMerge = require('deep-merge');
var Mocha = require('mocha');
var deepmerge = DeepMerge(function(target, source) {
if(target instanceof Array) {
return [].concat(target, source);
}
return source;
});
// generic
var defaultConfig = {
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loaders: ['babel'] }
]
}
};
if(process.env.NODE_ENV !== 'production') {
defaultConfig.devtool = '#eval-source-map';
defaultConfig.debug = true;
}
function config(overrides) {
return deepmerge(defaultConfig, overrides || {});
}
function mochaTest(file, cb) {
var mocha = new Mocha;
mocha.addFile(file);
var runner = mocha.run();
runner.on('end', function() {
// mocha uses require to initialize it's suite. We are now watching the
// file so the file needs to be deleted from the cache.
// see https://github.com/mochajs/mocha/blob/master/bin/_mocha#L358
delete require.cache[file];
if (cb) { cb(); }
});
}
// backend
var mochaTestFile = path.join(__dirname, 'build/test/test.js');
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
var testConfig = config({
entry: './test/sanity_test.js',
target: 'node',
output: {
path: path.join(__dirname, 'build/test'),
filename: 'test.js'
},
node: {
__dirname: true,
__filename: true
},
externals: nodeModules,
plugins: [
new webpack.IgnorePlugin(/\.(css|less)$/),
new webpack.BannerPlugin('require("source-map-support").install();',
{ raw: true, entryOnly: false })
]
});
// tasks
function onBuild(done) {
return function(err, stats) {
if(err) {
console.log('Error', err);
}
else {
console.log(stats.toString());
}
if(done) {
done();
}
};
}
gulp.task('test-build', function(done) {
webpack(testConfig).run(function(err, stats) {
onBuild()(err, stats);
mochaTest(mochaTestFile, done);
});
});
gulp.task('test-watch', function() {
webpack(testConfig).watch(100, function(err, stats) {
onBuild()(err, stats);
mochaTest(mochaTestFile);
});
});
@tcoopman
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment