Skip to content

Instantly share code, notes, and snippets.

@Joris-van-der-Wel
Last active September 19, 2015 12:38
Show Gist options
  • Save Joris-van-der-Wel/f0b02271b1f1bcb5c527 to your computer and use it in GitHub Desktop.
Save Joris-van-der-Wel/f0b02271b1f1bcb5c527 to your computer and use it in GitHub Desktop.
jsdom node-unit to mocha
#!/usr/bin/env node
"use strict";
const fs = require("fs");
const nodePath = require("path");
const childProcess = require("child_process");
const fileName = nodePath.resolve(process.argv[2]);
const async = process.argv[3] === "async";
const requires = `
const t = require("chai").assert;
const describe = require("mocha").describe;
const it = require("mocha").it;
`;
const suiteName = fileName
.replace(/\\/g, "/")
.replace(/\.js$/, "")
.replace(/^.*\/test\//, "");
let fileContent = fs.readFileSync(fileName, "utf8");
fileContent = /([\s\S]+?)^(exports\[[\s\S]+)/m.exec(fileContent);
let testHead = fileContent[1];
let testBody = fileContent[2];
testHead = testHead.replace(/^\s*(["']use strict["'];)\s*$/m, "$1\n" + requires);
// remove t.done(), mocha case is not async by default
testBody = testBody.replace(/(\s*)t.done\(\);\s*$/gm, async ? "$1done();\n" : "");
// there is no equivalent for t.expect(123);
testBody = testBody.replace(/\s*t.expect\(\d+\);\s*$/gm, "");
testBody = testBody.replace(/^exports\[(.*?)\]\s*=.*$/gm, async ? "it($1, done => {" : "it($1, () => {");
testBody = testBody.replace(/^};\s*$/gm, "});\n");
// place within a describe block (and indent)
testBody = testBody.replace(/(^)(.)/mg, "$1 $2");
testBody = "describe(\"" + suiteName + "\", () => {\n\n" + testBody + "\n});\n";
//console.log(testHead + testBody);
fs.writeFileSync(fileName, testHead + testBody, "utf8");
const verifyCommand = "(jshint " + fileName + " && jscs " + fileName + " && mocha " + fileName + ")";
console.log(verifyCommand);
childProcess.exec(verifyCommand, {
encoding: "utf8",
shell: "/bin/bash",
stdio: [null, "pipe", "pipe"]
}, (error, stderr, stdout) => {
console.error(error);
console.error(stderr);
console.log(stdout);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment