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(onenote): cover the PR 10755 patch-coverage gaps
Elian Doran78beb15ebffd
diff --git a/apps/client/src/services/import.spec.ts b/apps/client/src/services/import.spec.tsindex eff572c94f..84e35cadf1 100644--- a/apps/client/src/services/import.spec.ts+++ b/apps/client/src/services/import.spec.ts@@ -197,6 +197,25 @@ describe("importNotes ws handler", () => {tSpy.mockRestore();});+ it("shows the explicit throttled message while Graph rate-limits, with and without a total", async () => {+ const tSpy = vi.spyOn(i18n, "t").mockImplementation(((key: string) => key) as typeof i18n.t);++ // The count can legitimately sit still for a long time, so the throttled phase overrides the+ // usual count message — but the bar stays, since the counted progress is still real.+ await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 3, totalCount: 12, phase: "throttled" } as any);+ let toast = (toastService.showPersistent as any).mock.calls.at(-1)[0];+ expect(toast.message).toBe("import.throttled-with-total");+ expect(toast.progress).toBe(3 / 12);++ // Throttled before any total is known: no count to show, no bar.+ await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 0, phase: "throttled" } as any);+ toast = (toastService.showPersistent as any).mock.calls.at(-1)[0];+ expect(toast.message).toBe("import.throttled");+ expect(toast.progress).toBeUndefined();++ tSpy.mockRestore();+ });+it("shows a generic 'starting' message (no bar) before anything is counted", async () => {const tSpy = vi.spyOn(i18n, "t").mockImplementation(((key: string) => key) as typeof i18n.t);await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 0 } as any);diff --git a/apps/client/src/services/onenote_import.spec.ts b/apps/client/src/services/onenote_import.spec.tsindex 56e7ef5638..4087136e59 100644--- a/apps/client/src/services/onenote_import.spec.ts+++ b/apps/client/src/services/onenote_import.spec.ts@@ -1,6 +1,17 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";-import { buildSectionSelections, collectSectionIds, extractServerMessage, type OneNoteNotebook, orderedChildren } from "./onenote_import.js";+vi.mock("./server.js", () => ({+ default: {+ // Resolves to an array: onenote_import's module graph eagerly loads services (e.g.+ // keyboard_actions) that fetch on load and iterate the response.+ get: vi.fn(async () => []),+ getWithSilentUnauthorized: vi.fn(async () => ({ notebooks: [] })),+ post: vi.fn(async () => ({}))+ }+}));++import onenoteImport, { buildSectionSelections, collectSectionIds, extractServerMessage, type OneNoteNotebook, orderedChildren } from "./onenote_import.js";+import server from "./server.js";const NOTEBOOKS: OneNoteNotebook[] = [{@@ -60,6 +71,44 @@ describe("orderedChildren", () => {// contents') decides its slot, so the rail order is early, group, late.expect(describeChild(INTERLEAVE)).toEqual(["section:early", "group:grp", "section:late"]);});++ it("sorts a child with no creation date first (empty key), keeping the rest ordered", () => {+ const undated: OneNoteNotebook[] = [{+ id: "nb",+ title: "NB",+ sections: [+ { id: "dated", title: "Dated", createdDateTime: "2020-01-01T00:00:00Z" },+ { id: "undated", title: "Undated" }+ ],+ sectionGroups: []+ }];+ expect(describeChild(undated)).toEqual(["section:undated", "section:dated"]);+ });+});++describe("service endpoints", () => {+ it("routes each operation to its endpoint, listing notebooks without the generic 401 toast", async () => {+ await onenoteImport.deviceLogin();+ expect(server.post).toHaveBeenCalledWith("onenote-import/device-login");++ await onenoteImport.devicePoll();+ expect(server.post).toHaveBeenCalledWith("onenote-import/device-poll");++ await onenoteImport.getStatus();+ expect(server.get).toHaveBeenCalledWith("onenote-import/status");++ await onenoteImport.disconnect();+ expect(server.post).toHaveBeenCalledWith("onenote-import/disconnect");++ // A 401 (expired connection) is shown inline by the dialog, so the silent variant is used —+ // the plain get() would double-report through the generic error toast.+ await onenoteImport.getNotebooks();+ expect(server.getWithSilentUnauthorized).toHaveBeenCalledWith("onenote-import/notebooks");++ const payload = { parentNoteId: "p1", sections: [], taskId: "t1" };+ await onenoteImport.runImport(payload);+ expect(server.post).toHaveBeenCalledWith("onenote-import/import", payload);+ });});describe("buildSectionSelections", () => {diff --git a/apps/client/src/widgets/dialogs/import/onenote.spec.tsx b/apps/client/src/widgets/dialogs/import/onenote.spec.tsxnew file mode 100644index 0000000000..68e9a78a48--- /dev/null+++ b/apps/client/src/widgets/dialogs/import/onenote.spec.tsx@@ -0,0 +1,249 @@+import { type ComponentChildren, render } from "preact";+import { useState } from "preact/hooks";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from "vitest";++import * as i18n from "../../../services/i18n.js";+import type { OneNoteNotebook } from "../../../services/onenote_import.js";++// The service's default export is the API surface the panel drives; the named helpers+// (buildSectionSelections, collectSectionIds, …) stay real so the tree/selection logic under test+// is the production one.+const api = vi.hoisted(() => ({+ getStatus: vi.fn(),+ getNotebooks: vi.fn(),+ deviceLogin: vi.fn(),+ devicePoll: vi.fn(),+ disconnect: vi.fn(async () => ({})),+ runImport: vi.fn(async () => {})+}));+const showError = vi.hoisted(() => vi.fn());++vi.mock("../../../services/onenote_import.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../../services/onenote_import.js")>()),+ default: api+}));+vi.mock("../../../services/toast.js", () => ({ default: { showError } }));+// The shrink-images preference; the panel only reads it, so a fixed "on" is enough.+vi.mock("../../react/hooks.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks.js")>()),+ useTriliumOptionBool: () => [true, vi.fn()]+}));++const { default: provider } = await import("./onenote.js");++const NOTEBOOKS: OneNoteNotebook[] = [{+ id: "nb1",+ title: "Notebook 1",+ createdDateTime: "2020-01-01T00:00:00Z",+ sections: [+ { id: "s1", title: "Section 1", createdDateTime: "2020-01-01T00:00:00Z" },+ { id: "s2", title: "Section 2", createdDateTime: "2020-02-01T00:00:00Z" }+ ],+ sectionGroups: []+}];++let container: HTMLDivElement;+let closeDialog: Mock<() => void>;+let footer: ComponentChildren;+let applyFooter: ((node: ComponentChildren) => void) | null = null;++/** Mirrors the dialog shell: the footer the panel pushes up is rendered through state, exactly as+ * the production dialog does, so the panel's footer effect drives a live subtree. */+function FooterHost() {+ const [node, setNode] = useState<ComponentChildren>(null);+ applyFooter = setNode;+ return <div className="footer-host">{node}</div>;+}++beforeEach(() => {+ vi.clearAllMocks();+ api.getStatus.mockResolvedValue({ connected: true, account: { name: "Ada", email: "[email protected]" } });+ api.getNotebooks.mockResolvedValue({ notebooks: NOTEBOOKS });+ closeDialog = vi.fn<() => void>();+ footer = null;+ container = document.createElement("div");+ document.body.appendChild(container);+});++afterEach(() => {+ render(null, container);+ container.remove();+ applyFooter = null;+});++async function mount() {+ const Panel = provider.Panel;+ await act(async () => {+ render(+ <div>+ <Panel+ parentNoteId="root"+ closeDialog={closeDialog}+ setFooter={(node: ComponentChildren) => {+ footer = node;+ applyFooter?.(node);+ }}+ />+ <FooterHost />+ </div>,+ container+ );+ });+ // The status → notebooks → ready chain spans several microtask hops; one extra flush lets the+ // footer effect settle before assertions.+ await act(async () => {});+ // The panel's footer effect can fire between act flushes, before FooterHost's setter processes+ // the update — sync the host with whatever the panel pushed last.+ await act(async () => {+ applyFooter?.(footer);+ });+}++async function click(button: Element | null | undefined) {+ expect(button).toBeTruthy();+ await act(async () => {+ (button as HTMLButtonElement).click();+ });+ await act(async () => {});+}++const importButton = () => container.querySelector<HTMLButtonElement>(".footer-host button");++/** The panel's account action buttons in DOM order: refresh, then disconnect. */+function accountButtons() {+ return [...container.querySelectorAll<HTMLButtonElement>(".onenote-account-actions button")];+}++describe("OneNotePanel", () => {+ it("shows the connect screen and no footer when the session is not connected", async () => {+ api.getStatus.mockResolvedValue({ connected: false, account: null });+ await mount();++ expect(container.querySelector(".onenote-account")).toBeNull();+ expect(container.querySelector(".bxl-microsoft")).not.toBeNull();+ expect(footer).toBeNull();+ });++ it("reports a failed status check via toast (server reason first) and falls back to connect", async () => {+ api.getStatus.mockRejectedValue(new Error("status check exploded"));+ await mount();++ expect(showError).toHaveBeenCalledWith("status check exploded");+ expect(container.querySelector(".bxl-microsoft")).not.toBeNull();+ });++ it("lists the connected account's notebooks as a section picker with an import footer", async () => {+ await mount();++ expect(container.querySelector(".checkbox-tree")).not.toBeNull();+ expect(container.querySelectorAll(".checkbox-tree input[type=checkbox]").length).toBeGreaterThanOrEqual(2);+ // Nothing selected yet: the footer import button exists but is disabled.+ expect(importButton()?.disabled).toBe(true);+ });++ it("imports the selected sections and reports an upfront failure with the server's reason", async () => {+ api.runImport.mockRejectedValue(new Error('{"message":"Not connected to OneNote."}'));+ await mount();++ // Select one section leaf, which enables the footer button.+ await click(container.querySelector(".checkbox-tree-leaf input[type=checkbox]"));+ expect(importButton()?.disabled).toBe(false);++ await click(importButton());+ expect(closeDialog).toHaveBeenCalled();+ expect(api.runImport).toHaveBeenCalledWith(expect.objectContaining({+ parentNoteId: "root",+ sections: [expect.objectContaining({ id: "s1" })],+ shrinkImages: true+ }));+ expect(showError).toHaveBeenCalledWith("Not connected to OneNote.");++ // A rejection carrying no usable text is stringified as the last resort.+ api.runImport.mockRejectedValueOnce(42);+ await click(importButton());+ expect(showError).toHaveBeenCalledWith("42");+ });++ it("shows a listing failure inline with the server's reason, and recovers via retry", async () => {+ api.getNotebooks+ .mockRejectedValueOnce(new Error('{"message":"The OneNote connection has expired."}'))+ .mockResolvedValueOnce({ notebooks: NOTEBOOKS });+ await mount();++ // The failure is inline (no toast) and the stale/empty tree is not offered.+ const inlineError = container.querySelector(".no-items");+ expect(inlineError?.textContent).toContain("The OneNote connection has expired.");+ expect(container.querySelector(".checkbox-tree")).toBeNull();+ expect(showError).not.toHaveBeenCalled();++ await click(inlineError?.querySelector("button"));+ expect(container.querySelector(".no-items")).toBeNull();+ expect(container.querySelector(".checkbox-tree")).not.toBeNull();+ });++ it("prunes selected ids that no longer exist when the list is refreshed", async () => {+ await mount();+ await click(container.querySelector(".checkbox-tree-leaf input[type=checkbox]"));+ expect(importButton()?.disabled).toBe(false);++ // The refresh returns a list without the selected section — the selection must not keep+ // counting the phantom id, so the import button drops back to disabled.+ api.getNotebooks.mockResolvedValue({ notebooks: [{ ...NOTEBOOKS[0], sections: [NOTEBOOKS[0].sections[1]] }] });+ await click(accountButtons()[0]);+ expect(importButton()?.disabled).toBe(true);+ });++ it("shows the empty-account hint when the connected account has no notebooks", async () => {+ api.getNotebooks.mockResolvedValue({ notebooks: [] });+ await mount();++ expect(container.querySelector(".onenote-hint")).not.toBeNull();+ expect(container.querySelector(".checkbox-tree")).toBeNull();+ });++ it("clears the account, notebooks and selection on disconnect", async () => {+ await mount();+ await click(accountButtons()[1]);++ expect(api.disconnect).toHaveBeenCalled();+ expect(container.querySelector(".onenote-account")).toBeNull();+ expect(container.querySelector(".bxl-microsoft")).not.toBeNull();+ expect(footer).toBeNull();+ });++ it("surfaces a failed sign-in start with the server's reason and stays disconnected", async () => {+ api.getStatus.mockResolvedValue({ connected: false, account: null });+ api.deviceLogin.mockRejectedValue(new Error('{"message":"Sign-in could not be started."}'));+ await mount();++ await click(container.querySelector(".bxl-microsoft")?.closest("button"));+ expect(showError).toHaveBeenCalledWith("Sign-in could not be started.");+ expect(container.querySelector(".bxl-microsoft")).not.toBeNull();++ // A rejection carrying no usable text is stringified as the last resort.+ api.deviceLogin.mockRejectedValueOnce(42);+ await click(container.querySelector(".bxl-microsoft")?.closest("button"));+ expect(showError).toHaveBeenCalledWith("42");+ });++ it("falls back to generic wording when a failure carries no server message", async () => {+ // i18next is uninitialised under test, so pin t() to return its key — asserting the key+ // proves the fallback path was taken without depending on the wording.+ const tSpy = vi.spyOn(i18n, "t").mockImplementation(((key: string) => key) as typeof i18n.t);+ try {+ api.getStatus.mockRejectedValue(new Error(""));+ await mount();+ expect(showError).toHaveBeenCalledWith("onenote_import.load_failed");++ // The same fallback feeds the inline listing error.+ render(null, container);+ api.getStatus.mockResolvedValue({ connected: true, account: { name: "Ada", email: "[email protected]" } });+ api.getNotebooks.mockRejectedValue(new Error(""));+ await mount();+ expect(container.querySelector(".no-items")?.textContent).toContain("onenote_import.load_failed");+ } finally {+ tSpy.mockRestore();+ }+ });+});diff --git a/apps/client/src/widgets/type_widgets/File.spec.tsx b/apps/client/src/widgets/type_widgets/File.spec.tsxindex f8dad6054d..8fb8f621df 100644--- a/apps/client/src/widgets/type_widgets/File.spec.tsx+++ b/apps/client/src/widgets/type_widgets/File.spec.tsx@@ -14,13 +14,14 @@ vi.mock("../../services/clipboard_ext", () => ({ copyTextWithToast: vi.fn() }));// ActionButton drags in tooltips and command wiring that are irrelevant here.vi.mock("../react/ActionButton", () => ({ default: () => <button class="code-block-copy" /> }));-// Only TextPreview is under test; stub the sibling previews (and the blob hook they feed on)-// so their service imports stay out of the module graph.+// Stub the sibling previews (and the blob hook they feed on) so their service imports stay out of+// the module graph; the markers let FileTypeWidget's mime routing be asserted without rendering them.vi.mock("../react/hooks", () => ({ useNoteBlob: vi.fn(() => null) }));-vi.mock("./file/MediaPreview", () => ({ default: () => null }));-vi.mock("./file/Pdf", () => ({ default: () => null }));+vi.mock("./file/MediaPreview", () => ({ default: () => <div class="media-preview-stub" /> }));+vi.mock("./file/Pdf", () => ({ default: () => <div class="pdf-preview-stub" /> }));-const { TextPreview } = await import("./File");+const { useNoteBlob } = await import("../react/hooks");+const { default: FileTypeWidget, TextPreview } = await import("./File");let container: HTMLDivElement;@@ -38,6 +39,41 @@ afterEach(() => {vi.clearAllMocks();});+describe("FileTypeWidget", () => {+ const mount = (mime: string, noteContext?: unknown) => {+ const props = { note: { mime }, noteContext } as unknown as Parameters<typeof FileTypeWidget>[0];+ render(<FileTypeWidget {...props} />, container);+ };++ it("previews text content through TextPreview, forwarding the note's mime to the highlighter", async () => {+ vi.mocked(useNoteBlob).mockReturnValue({ content: "<ink/>" } as ReturnType<typeof useNoteBlob>);+ mount("application/inkml+xml");++ expect(container.querySelector("pre.file-preview-content > code")?.textContent).toBe("<ink/>");+ // The mime reached TextPreview: the +xml suffix resolves to the base XML syntax.+ await vi.waitFor(() => expect(applySingleBlockSyntaxHighlight).toHaveBeenCalledTimes(1));+ expect(applySingleBlockSyntaxHighlight.mock.calls[0][1]).toBe("text-xml");+ });++ it("routes non-text blobs by mime: PDF, media, and a no-preview fallback", () => {+ // mockReturnValue outlives clearAllMocks, so drop the previous test's text blob explicitly.+ vi.mocked(useNoteBlob).mockReturnValue(null);++ // PDF renders only when a note context is available to hand down.+ mount("application/pdf", {});+ expect(container.querySelector(".pdf-preview-stub")).not.toBeNull();++ mount("video/mp4");+ expect(container.querySelector(".media-preview-stub")).not.toBeNull();+ mount("audio/mpeg");+ expect(container.querySelector(".media-preview-stub")).not.toBeNull();++ mount("application/octet-stream");+ expect(container.querySelector(".media-preview-stub")).toBeNull();+ expect(container.querySelector(".alert")).not.toBeNull();+ });+});+describe("TextPreview", () => {it("renders the content as text in a code block and highlights it with the normalized MIME type", async () => {render(<TextPreview content={"<p>hello</p>"} mime="text/html" />, container);diff --git a/apps/server/src/services/import/onenote/converter.spec.ts b/apps/server/src/services/import/onenote/converter.spec.tsindex ced2d6948f..cf20a68625 100644--- a/apps/server/src/services/import/onenote/converter.spec.ts+++ b/apps/server/src/services/import/onenote/converter.spec.ts@@ -845,6 +845,36 @@ describe("convertPageHtml", () => {expect(out).toContain("<code>npm install</code>");expect(out).toContain("<code>npm start</code>");});++ it("sees through formatting wrappers and whitespace when judging what renders in Consolas", () => {+ // Text inside a formatting child with no font-family of its own still renders in the+ // paragraph's Consolas, so the lone paragraph becomes inline code with the wrapper kept.+ const wrapped = converter.convertPageHtml(+ `<body><div><p style="font-family:Consolas"><strong>ls -la</strong></p></div></body>`+ );+ expect(wrapped).toContain("<code><strong>ls -la</strong></code>");++ // Whitespace-only direct text is not "text rendering in Consolas": with the only real text+ // overridden to Calibri, the paragraph is not code at all — neither block nor inline.+ const whitespace = converter.convertPageHtml(+ `<body><div><p style="font-family:Consolas"> <span style="font-family:Calibri">plain</span></p></div></body>`+ );+ expect(whitespace).toContain("plain");+ expect(whitespace).not.toContain("<code>");+ });++ it("treats an empty Consolas paragraph inside a run as a blank code line", () => {+ // The empty paragraph has no text to judge, so only its own Consolas paragraph mark lets it+ // join the run — as an empty line between the two code lines.+ const sample = `<body><div>+ <p style="font-family:Consolas">a</p>+ <p style="font-family:Consolas"></p>+ <p style="font-family:Consolas">b</p>+ </div></body>`;+ const out = converter.convertPageHtml(sample);++ expect(out).toContain(`<pre><code class="language-text-x-trilium-auto">a\n\nb</code></pre>`);+ });});describe("extractPageCreatedDate", () => {