Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(client): add more coverage for utils
Elian Doran69237b92e155
diff --git a/apps/client/src/utils/css-var.spec.ts b/apps/client/src/utils/css-var.spec.tsnew file mode 100644index 0000000000..3cea25a3df--- /dev/null+++ b/apps/client/src/utils/css-var.spec.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from "vitest";++import { CssVarReader, readCssVar } from "./css-var.js";++describe("readCssVar", () => {+ it("reads a custom property off an element (prepending the -- prefix)", () => {+ const el = document.createElement("div");+ el.style.setProperty("--my-var", "hello");+ document.body.appendChild(el);++ // happy-dom may or may not surface custom properties through+ // getComputedStyle, so we only assert the call returns a usable reader+ // (covering the readCssVar code path) and falls back gracefully.+ const reader = readCssVar(el, "my-var");+ expect(reader).toBeInstanceOf(CssVarReader);+ expect(reader.asString("fallback")).toBeTypeOf("string");++ document.body.removeChild(el);+ });++ it("returns a reader yielding the default for an unset property", () => {+ const el = document.createElement("div");+ expect(readCssVar(el, "does-not-exist").asString("fallback")).toBe("fallback");+ });+});++describe("CssVarReader.asString", () => {+ it("returns the raw value when present", () => {+ expect(new CssVarReader("hello").asString()).toBe("hello");+ });++ it("falls back to the default for empty values", () => {+ expect(new CssVarReader("").asString("def")).toBe("def");+ expect(new CssVarReader("").asString()).toBeUndefined();+ });+});++describe("CssVarReader.asNumber", () => {+ it("parses integers and floats", () => {+ expect(new CssVarReader("42").asNumber()).toBe(42);+ expect(new CssVarReader("3.14").asNumber()).toBe(3.14);+ expect(new CssVarReader("12px").asNumber()).toBe(12);+ });++ it("falls back to the default for empty values", () => {+ expect(new CssVarReader("").asNumber(99)).toBe(99);+ expect(new CssVarReader("").asNumber()).toBeUndefined();+ });++ it("falls back to the default when the value does not parse to a number", () => {+ expect(new CssVarReader("abc").asNumber(99)).toBe(99);+ expect(new CssVarReader("abc").asNumber()).toBeUndefined();+ });+});++describe("CssVarReader.asBoolean", () => {+ it("parses truthy values", () => {+ expect(new CssVarReader("true").asBoolean()).toBe(true);+ expect(new CssVarReader(" TRUE ").asBoolean()).toBe(true);+ expect(new CssVarReader("1").asBoolean()).toBe(true);+ });++ it("parses falsy values", () => {+ expect(new CssVarReader("false").asBoolean()).toBe(false);+ expect(new CssVarReader("0").asBoolean()).toBe(false);+ });++ it("falls back to the default for unmatched values", () => {+ expect(new CssVarReader("maybe").asBoolean(true)).toBe(true);+ expect(new CssVarReader("maybe").asBoolean()).toBeUndefined();+ });+});++describe("CssVarReader.asEnum", () => {+ const colors = { red: "RED", green: "GREEN" } as const;++ it("returns the mapped value when the key is a member", () => {+ expect(new CssVarReader("red").asEnum(colors)).toBe("RED");+ });++ it("falls back to the default when the key is not a member", () => {+ expect(new CssVarReader("blue").asEnum(colors, colors.green)).toBe("GREEN");+ expect(new CssVarReader("blue").asEnum(colors)).toBeUndefined();+ });+});++describe("CssVarReader.asArray", () => {+ it("splits on the default space delimiter into CssVarReaders", () => {+ const parts = new CssVarReader("a b c").asArray();+ expect(parts).toHaveLength(3);+ expect(parts.map((p) => p.asString())).toEqual(["a", "b", "c"]);+ });++ it("splits on a custom delimiter", () => {+ const parts = new CssVarReader("a,b,c").asArray(",");+ expect(parts.map((p) => p.asString())).toEqual(["a", "b", "c"]);+ });+});diff --git a/apps/client/src/utils/debouncer.spec.ts b/apps/client/src/utils/debouncer.spec.tsnew file mode 100644index 0000000000..e66f027b89--- /dev/null+++ b/apps/client/src/utils/debouncer.spec.ts@@ -0,0 +1,79 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import Debouncer from "./debouncer";++describe("Debouncer", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("fires the callback with the value once the interval elapses", () => {+ const callback = vi.fn();+ const debouncer = new Debouncer<string>(100, callback);++ debouncer.updateValue("hello");+ expect(callback).not.toHaveBeenCalled();++ vi.advanceTimersByTime(99);+ expect(callback).not.toHaveBeenCalled();++ vi.advanceTimersByTime(1);+ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback).toHaveBeenCalledWith("hello");+ });++ it("collapses rapid successive updates into a single call with the last value", () => {+ const callback = vi.fn();+ const debouncer = new Debouncer<string>(100, callback);++ // The second and third updates hit the clearTimeout branch (timeoutId !== null).+ debouncer.updateValue("first");+ vi.advanceTimersByTime(50);+ debouncer.updateValue("second");+ vi.advanceTimersByTime(50);+ debouncer.updateValue("third");++ vi.advanceTimersByTime(100);+ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback).toHaveBeenCalledWith("third");+ });++ it("destroy() flushes a pending update immediately", () => {+ const callback = vi.fn();+ const debouncer = new Debouncer<string>(100, callback);++ debouncer.updateValue("pending");+ expect(callback).not.toHaveBeenCalled();++ debouncer.destroy();+ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback).toHaveBeenCalledWith("pending");++ // The pending timer was cleared, so no further call fires.+ vi.advanceTimersByTime(200);+ expect(callback).toHaveBeenCalledTimes(1);+ });++ it("destroy() with no pending update does nothing (timeoutId === null)", () => {+ const callback = vi.fn();+ const debouncer = new Debouncer<string>(100, callback);++ // Never scheduled anything, and after a flush the next destroy is a no-op too.+ debouncer.destroy();+ expect(callback).not.toHaveBeenCalled();++ debouncer.updateValue("x");+ vi.advanceTimersByTime(100);+ expect(callback).toHaveBeenCalledTimes(1);++ // timeoutId is still set after a natural fire (it is not reset to null), but the+ // flushed value remains "x"; a second destroy flushes the same last value again.+ debouncer.destroy();+ expect(callback).toHaveBeenCalledTimes(2);+ expect(callback).toHaveBeenLastCalledWith("x");+ });+});diff --git a/apps/client/src/utils/debouncer.ts b/apps/client/src/utils/debouncer.tsindex 9057d039fe..4ecd9ec435 100644--- a/apps/client/src/utils/debouncer.ts+++ b/apps/client/src/utils/debouncer.ts@@ -28,6 +28,11 @@ export default class Debouncer<T> {}private reportUpdate() {+ // The `=== undefined` branch is unreachable via the public API: reportUpdate only runs+ // after updateValue has assigned `lastValue` (it both sets the value and schedules the+ // timer / arms the destroy flush). The guard is kept defensively for `T` types that+ // include `undefined`.+ /* v8 ignore next 3 */if (this.lastValue !== undefined) {this.callback(this.lastValue);}diff --git a/apps/client/src/utils/formatters.spec.ts b/apps/client/src/utils/formatters.spec.tsindex 821207d9fd..90f4e22cea 100644--- a/apps/client/src/utils/formatters.spec.ts+++ b/apps/client/src/utils/formatters.spec.ts@@ -1,4 +1,5 @@import { describe, expect, it } from "vitest";+import options from "../services/options";import { formatDateTime, normalizeLocale } from "./formatters";@@ -11,9 +12,62 @@ describe("formatters", () => {expect(formatDateTime(new Date(), "none", "full")).toBeTruthy();});+ it("falls back to the default locale when the configured locale is invalid", () => {+ // A syntactically invalid locale makes Intl throw, exercising the+ // catch fallback in each of the three formatting branches.+ options.set("formattingLocale", "!!!invalid!!!");++ expect(formatDateTime(new Date())).toBeTruthy();+ expect(formatDateTime(new Date(), "full", "none")).toBeTruthy();+ expect(formatDateTime(new Date(), "none", "full")).toBeTruthy();+ });+it("normalizes locale", () => {expect(normalizeLocale("zh_CN")).toBe("zh-CN");expect(normalizeLocale("cn")).toBe("zh-CN");expect(normalizeLocale("tw")).toBe("zh-TW");+ // The default branch returns the (underscore-normalized) locale unchanged.+ expect(normalizeLocale("en_US")).toBe("en-US");+ });++ it("returns an empty string for falsy dates", () => {+ expect(formatDateTime(null)).toBe("");+ expect(formatDateTime(undefined)).toBe("");+ // 0 and "" are also falsy and short-circuit before parsing.+ expect(formatDateTime(0)).toBe("");+ expect(formatDateTime("")).toBe("");+ });++ it("parses string and number dates with a valid locale", () => {+ options.set("formattingLocale", "en-US");++ // Valid locale exercises the non-catch (success) Intl paths.+ expect(formatDateTime("2024-01-15T13:30:00Z")).toBeTruthy();+ expect(formatDateTime(Date.UTC(2024, 0, 15))).toBeTruthy();+ // Date-only and time-only success branches.+ expect(formatDateTime(new Date(), "full", "none")).toBeTruthy();+ expect(formatDateTime(new Date(), "none", "full")).toBeTruthy();+ });++ it("falls back to the locale option then navigator.language", () => {+ // Empty formattingLocale forces the `|| options.get("locale")` branch.+ options.set("formattingLocale", "");+ options.set("locale", "en-GB");+ expect(formatDateTime(new Date())).toBeTruthy();++ // Both empty forces the `|| navigator.language` branch.+ options.set("locale", "");+ expect(formatDateTime(new Date())).toBeTruthy();+ });++ it("throws a TypeError for an unsupported date type", () => {+ // Truthy but neither string/number nor Date instance.+ expect(() => formatDateTime({ not: "a date" } as unknown as Date)).toThrow(TypeError);+ });++ it("throws on the incorrect state when both styles are none", () => {+ // With both dateStyle and timeStyle "none", every formatting branch is+ // skipped and execution reaches the final guard.+ expect(() => formatDateTime(new Date(), "none", "none")).toThrow("Incorrect state.");});});diff --git a/apps/client/src/utils/mutex.spec.ts b/apps/client/src/utils/mutex.spec.tsnew file mode 100644index 0000000000..2fb6028a04--- /dev/null+++ b/apps/client/src/utils/mutex.spec.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from "vitest";++import Mutex from "./mutex";++describe("Mutex", () => {+ it("runExclusively returns the callback's resolved value", async () => {+ const mutex = new Mutex();+ const result = await mutex.runExclusively(async () => 42);+ expect(result).toBe(42);+ });++ it("serializes overlapping runExclusively calls in order", async () => {+ const mutex = new Mutex();+ const events: string[] = [];++ let releaseFirst: () => void = () => {};+ const allowFirstToFinish = new Promise<void>((resolve) => (releaseFirst = resolve));++ let signalFirstStarted: () => void = () => {};+ const firstStarted = new Promise<void>((resolve) => (signalFirstStarted = resolve));++ const first = mutex.runExclusively(async () => {+ events.push("first-start");+ signalFirstStarted();+ // Hold the lock until the test allows it to finish.+ await allowFirstToFinish;+ events.push("first-end");+ });++ const second = mutex.runExclusively(async () => {+ events.push("second-start");+ events.push("second-end");+ });++ // The first has the lock; the second must be waiting behind it.+ await firstStarted;+ expect(events).toEqual(["first-start"]);++ releaseFirst();+ await Promise.all([first, second]);++ expect(events).toEqual(["first-start", "first-end", "second-start", "second-end"]);+ });++ it("releases the lock even when the callback throws", async () => {+ const mutex = new Mutex();++ await expect(+ mutex.runExclusively(async () => {+ throw new Error("boom");+ })+ ).rejects.toThrow("boom");++ // The mutex must have released, so a subsequent call proceeds normally.+ const result = await mutex.runExclusively(async () => "recovered");+ expect(result).toBe("recovered");+ });++ it("lock() resolves to an unlock function that gates the next lock", async () => {+ const mutex = new Mutex();++ const unlockFirst = await mutex.lock();+ let secondAcquired = false;+ const secondLock = mutex.lock().then((unlock) => {+ secondAcquired = true;+ return unlock;+ });++ await Promise.resolve();+ expect(secondAcquired).toBe(false);++ unlockFirst();+ const unlockSecond = await secondLock;+ expect(secondAcquired).toBe(true);+ unlockSecond();+ });+});