Skip to content

Build your personal knowledge base with Trilium Notes

6.5 KB
Raw Blame
// The client always runs with `preact/compat` loaded, and its `options.vnode` hook changes how
// every element renders (`onChange` on a text input is `input`, `onFocus` is `focusin`). Loaded
// here so a spec renders the same way whether or not its own imports reach compat.
import "preact/compat";

import { Modal } from "bootstrap";
import $ from "jquery";
import { afterAll, vi } from "vitest";

import { stubHighlightApi } from "./highlights";

// Top level, not in a beforeAll: vi.mock is hoisted either way, and nesting it only makes the order lie.
vi.mock("../services/ws.js", mockWebsocket);
vi.mock("../services/server.js", mockServer);

injectGlobals();
stubHighlightApi();
survivePendingModalCallbacks();
deferSelectionChange();
drainBootstrapTransitions();

function injectGlobals() {
    const uncheckedWindow = window as any;
    uncheckedWindow.$ = $;
    // some libraries (e.g. jquery.fancytree's ui-deps) expect the jQuery global, same as src/index.ts
    uncheckedWindow.jQuery = $;
    uncheckedWindow.WebSocket = () => {};
    uncheckedWindow.glob = {
        isMainWindow: true,
        baseApiUrl: "api/"
    };
}

/**
 * Keeps a disposed modal readable by the callbacks Bootstrap has already queued.
 *
 * `dispose()` nulls every property (twbs/bootstrap#37474) while the end of the opening is still
 * waiting on a `transitionend` that happy-dom never fires, so it runs against a disposed instance
 * some milliseconds later and throws where no test can catch it. A teardown that disposes a modal
 * is how a spec releases the focus trap, so leave values those callbacks can read.
 */
function survivePendingModalCallbacks() {
    const proto = Modal.prototype as unknown as Record<string, unknown>;
    const dispose = proto.dispose as () => void;

    proto.dispose = function (this: Record<string, unknown>) {
        dispose.call(this);
        this._config = { focus: false, backdrop: false, keyboard: false };
        this._element = document.createElement("noscript");
        this._dialog = this._element;
        this._focustrap = { activate() {}, deactivate() {} };
        this._backdrop = { show() {}, hide() {}, dispose() {} };
    };
}

/**
 * Fires `selectionchange` after the code that moved the selection, as browsers do.
 *
 * happy-dom dispatches it from inside `Selection.collapse()`. CodeMirror moves the DOM selection
 * during `EditorView.update()`, and its listener updates the view again, which throws
 * "Calls to EditorView.update are not allowed while an update is in progress".
 */
function deferSelectionChange() {
    const dispatch = document.dispatchEvent.bind(document);
    // happy-dom's `dispatchEvent()` calls itself again for each event phase.
    const deferred = new WeakSet<Event>();

    document.dispatchEvent = (event: Event) => {
        if (event.type !== "selectionchange" || deferred.has(event)) {
            return dispatch(event);
        }

        deferred.add(event);
        queueMicrotask(() => dispatch(event));
        return true;
    };
}

function mockWebsocket() {
    function subscribeToMessages(_callback: (message: unknown) => void) {
        // Do nothing.
    }

    function unsubscribeToMessage(_callback: (message: unknown) => void) {
        // Do nothing.
    }

    // Awaited before reading back what the server wrote. No write happens under test.
    async function waitForMaxKnownEntityChangeId() {}

    return {
        default: {
            subscribeToMessages,
            waitForMaxKnownEntityChangeId
        },
        // consumers also import these as named exports (e.g. useNoteIds); leaving them out makes
        // the subscription effect throw, which silently skips every later effect of the component
        subscribeToMessages,
        unsubscribeToMessage,
        waitForMaxKnownEntityChangeId,
        // Code that reports a failure this way is usually in a catch block, so an undefined export
        // here throws over the error being handled and loses whatever the component did about it.
        logError(_message: string) {}
    };
}

function mockServer() {
    async function get(url: string) {
        if (url === "options") {
            return {};
        }

        if (url === "keyboard-actions") {
            return [];
        }

        // Asked for by the icon picker as it opens, to sort the icons a note already wears first.
        if (url === "other/icon-usage") {
            return { iconClassToCountMap: {} };
        }

        if (url === "tree") {
            return {
                branches: [],
                notes: [],
                attributes: []
            };
        }

        console.warn(`Unsupported GET to mocked server: ${url}`);
    }

    async function post(url: string, data: object) {
        if (url === "tree/load") {
            throw new Error(`A module tried to load from the server the following notes: ${((data as any).noteIds || []).join(",")}\nThis is not supported, use Froca mocking instead and ensure the note exist in the mock.`);
        }
    }

    return {
        default: {
            get,

            // Froca's blob and attachment loads go through this variant; it only differs from `get`
            // in how it reports 404s, which the mock never produces, so share the same routing.
            getWithSilentNotFound: get,

            // A backend script run goes through this variant so its failure is reported against the
            // note rather than as a request that went wrong; it differs from `post` only in how it
            // reports a 500, which the mock never produces.
            postWithSilentInternalServerError: (url: string, data: object) => post(url, data),

            post,

            // Widgets that persist as the user edits (attribute writes, view configs) reach for
            // these; without them the write rejects and surfaces as an unhandled rejection rather
            // than as whatever the test was actually asserting.
            async put(_url: string, _data?: object) {},
            async remove(_url: string) {}
        }
    };
}

/**
 * Lets Bootstrap's transition timers run out before the file's environment is torn down.
 *
 * happy-dom runs no transitions, so Bootstrap ends each one with a `setTimeout()` of about 5ms that
 * dispatches `transitionend` itself. A file that ends with a dialog still opening or closing leaves
 * one pending, and once the window is gone its `new Event()` belongs to another realm than the
 * element, which throws outside any test.
 */
function drainBootstrapTransitions() {
    afterAll(() => new Promise((resolve) => setTimeout(resolve, 50)));
}