Skip to content

Instantly share code, notes, and snippets.

@louwers
Last active June 2, 2024 20:07

Revisions

  1. louwers revised this gist Jun 2, 2024. 1 changed file with 0 additions and 8 deletions.
    8 changes: 0 additions & 8 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -1,8 +0,0 @@
    <html>
    <head>
    <script type="module" src="all.test.js"></script>
    </head>
    <body>
    <main></main>
    </body>
    </html>
  2. louwers created this gist Jun 2, 2024.
    4 changes: 4 additions & 0 deletions all.test.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    // add tests here, comment out to disable
    import "./example.test.js";

    console.log("This should only show up when running tests");
    5 changes: 5 additions & 0 deletions example.test.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    import { test, assert } from "test.js";

    test("1+1", () => {
    assert(1 + 1 === 2);
    });
    8 changes: 8 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    <html>
    <head>
    <script type="module" src="all.test.js"></script>
    </head>
    <body>
    <main></main>
    </body>
    </html>
    38 changes: 38 additions & 0 deletions test.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    /** @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);
    }