Skip to content

Instantly share code, notes, and snippets.

@AWolf81
Last active March 6, 2020 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AWolf81/e5a25ced70709ead0e16a49fa63b0ff1 to your computer and use it in GitHub Desktop.
Save AWolf81/e5a25ced70709ead0e16a49fa63b0ff1 to your computer and use it in GitHub Desktop.
Run Mocha.js tests with html reporter from CLI with JSDOM
var Mocha = require('mocha'),
fs = require('fs'),
path = require('path');
const { JSDOM } = require('jsdom')
const dom = new JSDOM(`<html><body>
<div id="mocha"></div>
</body></html>`);
global.document = dom.window.document;
global.window = dom.window;
// mockCanvas code from https://github.com/jsdom/jsdom/issues/1782#issuecomment-337656878
function mockCanvas (window) {
window.HTMLCanvasElement.prototype.getContext = function () {
return {
fillRect: function() {},
clearRect: function(){},
getImageData: function(x, y, w, h) {
return {
data: new Array(w*h*4)
};
},
putImageData: function() {},
createImageData: function(){ return []},
setTransform: function(){},
drawImage: function(){},
save: function(){},
fillText: function(){},
restore: function(){},
beginPath: function(){},
moveTo: function(){},
lineTo: function(){},
closePath: function(){},
stroke: function(){},
translate: function(){},
scale: function(){},
rotate: function(){},
arc: function(){},
fill: function(){},
measureText: function(){
return { width: 0 };
},
transform: function(){},
rect: function(){},
clip: function(){},
};
}
window.HTMLCanvasElement.prototype.toDataURL = function () {
return "";
}
}
mockCanvas(global.window);
// Instantiate a Mocha instance.
var mocha = new Mocha({
reporter: 'html'
});
var testDir = './test'
// Add each .js file to the mocha instance
fs.readdirSync(testDir).filter(function(file) {
// Only keep the .js files
return file.substr(-3) === '.js';
}).forEach(function(file) {
mocha.addFile(
path.join(testDir, file)
);
});
// Run the tests.
mocha.run(function(failures) {
const resultHtml = global.document.getElementsByTagName('html')[0].outerHTML;
fs.writeFile('./result.html', resultHtml, function (err) {
if (err) throw err;
console.log('Saved html file!');
});
process.exitCode = failures ? 1 : 0; // exit with non-zero status if there were failures
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment