Last active
June 2, 2024 20:07
-
-
Save louwers/cfda804648d7bc47ebe0cb5b0aec5946 to your computer and use it in GitHub Desktop.
Simple Test Framework JavaScript (in browser)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// add tests here, comment out to disable | |
import "./example.test.js"; | |
console.log("This should only show up when running tests"); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { test, assert } from "test.js"; | |
test("1+1", () => { | |
assert(1 + 1 === 2); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @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