Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active May 27, 2021
Embed
What would you like to do?
export function __test__({ test }) {
test("xxx", () => {
console.log("ok");
});
}
console.log("...");
import nodeResolve from "@rollup/plugin-node-resolve";
const TEST_PKG_NAME = "@mizchi/testlib";
function tester() {
return {
name: "test",
banner() {
return `import { runTests } from "${TEST_PKG_NAME}"`;
},
footer() {
return `runTests({ matcher: null })`;
},
transform(code, id) {
let out = code;
if (code.match(/export\s+function\s+__test__\s*\(/)) {
out += `\nimport { register } from "${TEST_PKG_NAME}";
register("${id}", __test__);`;
out = out.replace(/export\s+function\s+__test__/, "function __test__");
}
return out;
},
};
}
export default {
input: "index.js",
output: {
file: "out.js",
format: "es",
},
plugins: [nodeResolve(), tester()],
};
const __entries = [];
const __tests = [];
export function register(name, fn) {
__entries.push({name, fn});
}
function test(name, fn) {
// console.log("name", name, fn);
__tests.push({name, fn});
}
const log = (...args) => console.log("[test]", ...args)
export async function runTests(opts = {}) {
const matcher = opts.matcher;
const errors = [];
for (const e of __entries) {
try {
if (matcher == null || matcher.exec(e.name)) {
e.fn({ test });
}
} catch (err) {
errors.push({error: 'initialize-error', name: e.name});
console.error(err);
}
}
for (const r of __tests) {
try {
await r.fn();
log("PASS", r.name);
} catch (err) {
errors.push({error: err, name: r.name});
log("ERROR", r.name);
}
}
log("done");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment