Skip to content

Instantly share code, notes, and snippets.

@louwers
Last active June 2, 2024 20:07
Show Gist options
  • Save louwers/cfda804648d7bc47ebe0cb5b0aec5946 to your computer and use it in GitHub Desktop.
Save louwers/cfda804648d7bc47ebe0cb5b0aec5946 to your computer and use it in GitHub Desktop.
Simple Test Framework JavaScript (in browser)
// add tests here, comment out to disable
import "./example.test.js";
console.log("This should only show up when running tests");
import { test, assert } from "test.js";
test("1+1", () => {
assert(1 + 1 === 2);
});
/** @type {[string, () => Promise<void> | void][]} */
const tests = [];
/**
*
* @param {string} description
* @param {() => Promise<void> | void} testFunc
*/
export async function test(description, testFunc) {
tests.push([description, testFunc]);
}
export async function runAllTests() {
const main = document.querySelector("main");
if (!(main instanceof HTMLElement)) throw new Error();
main.innerHTML = "";
for (const [description, testFunc] of tests) {
const newSpan = document.createElement("p");
try {
await testFunc();
newSpan.textContent = `✅ ${description}`;
} catch (err) {
const errorMessage =
err instanceof Error && err.message ? ` - ${err.message}` : "";
newSpan.textContent = `❌ ${description}${errorMessage}`;
}
main.appendChild(newSpan);
}
}
/**
* @param {any} val
*/
export function assert(val, message = "") {
if (!val) throw new Error(message);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment