Skip to content

Build your personal knowledge base with Trilium Notes

test: cover the uncovered patch lines flagged by Codecov on this branch

Elian Doran2f2af8f35bcc
diff --git a/apps/client/src/login.spec.tsx b/apps/client/src/login.spec.tsx
index 781c4a2f10..fe7323491a 100644
--- a/apps/client/src/login.spec.tsx
+++ b/apps/client/src/login.spec.tsx
@@ -156,6 +156,12 @@ describe("login App — SSO branch", () => {
expect(c.textContent).toContain("login.sso-wrong-account");
});
+ it("maps any non-wrong-account SSO error to the not-enrolled message", () => {
+ window.glob.login = { ssoEnabled: true, ssoIssuerName: "Google", totpEnabled: false, ssoError: "not_enrolled" };
+ const c = renderInto(<App />);
+ expect(c.textContent).toContain("login.sso-not-enrolled");
+ });
+
it("shows the generic connection-failure message when the provider was unreachable", () => {
window.glob.login = { ssoEnabled: true, ssoIssuerName: "Google", totpEnabled: false, ssoConnectionFailed: true };
const c = renderInto(<App />);
diff --git a/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx b/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx
index 75d579aa82..9ac081b459 100644
--- a/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx
+++ b/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx
@@ -1,12 +1,36 @@
import { render } from "preact";
import { act } from "preact/test-utils";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// Rendering TemplateNoteTypes pulls in BadgeWithDropdown → Dropdown, which wires real Bootstrap;
+// a fake instance is enough since only the menu contents are asserted (same prelude as Dropdown.spec).
+vi.mock("bootstrap", () => ({
+ Dropdown: { getOrCreateInstance: () => ({ show() {}, hide() {}, update() {}, dispose() {}, _menu: null }) },
+ Tooltip: Object.assign(class {}, { getInstance: () => null })
+}));
+
+// Stub only the Bootstrap-Tooltip hook (it drives the jQuery tooltip plugin, absent under happy-dom);
+// the rest of the hooks module — notably useTriliumEvent — stays real.
+const tooltipStub = vi.hoisted(() => ({ showTooltip: () => {}, hideTooltip: () => {} }));
+vi.mock("../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../react/hooks")>()),
+ useTooltip: () => tooltipStub
+}));
import Component from "../../components/component.js";
import type FNote from "../../entities/fnote.js";
+import server from "../../services/server.js";
import { buildNote } from "../../test/easy-froca.js";
import { ParentComponent } from "../react/react_utils.js";
-import { useBuiltinTemplates } from "./NoteTypeSwitcher.js";
+import { TemplateNoteTypes, useBuiltinTemplates } from "./NoteTypeSwitcher.js";
+
+// happy-dom has no ResizeObserver; Dropdown only needs observe/disconnect to exist.
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+globalThis.ResizeObserver = globalThis.ResizeObserver ?? (ResizeObserverStub as unknown as typeof ResizeObserver);
let container: HTMLDivElement;
@@ -39,6 +63,43 @@ async function flush() {
}
}
+describe("TemplateNoteTypes", () => {
+ it("re-resolves user templates on frocaReloaded (fresh FNote refs after unlock)", async () => {
+ buildNote({ id: "userTemplate1", title: "[protected]" });
+ const serverGetSpy = vi.spyOn(server, "get").mockResolvedValue([ "userTemplate1" ]);
+
+ const host = new Component();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ act(() => render(
+ <ParentComponent.Provider value={host}>
+ <TemplateNoteTypes noteId="someNote" builtinTemplates={[]} />
+ </ParentComponent.Provider>,
+ container
+ ));
+ await flush();
+ expect(serverGetSpy).toHaveBeenCalledWith("search-templates");
+
+ // Unlock rebuilds froca: same noteId, new FNote instance with the decrypted title.
+ buildNote({ id: "userTemplate1", title: "Meeting Notes" });
+ serverGetSpy.mockClear();
+ await act(async () => { await host.handleEvent("frocaReloaded", {}); });
+ await flush();
+ expect(serverGetSpy).toHaveBeenCalledWith("search-templates");
+
+ // The dropdown renders its items only while open; opening is driven by Bootstrap's event.
+ const dropdown = container.querySelector(".dropdown");
+ expect(dropdown).not.toBeNull();
+ await act(async () => {
+ if (dropdown) window.$(dropdown).trigger("show.bs.dropdown");
+ });
+ expect(container.textContent).toContain("Meeting Notes");
+ expect(container.textContent).not.toContain("[protected]");
+
+ serverGetSpy.mockRestore();
+ });
+});
+
describe("useBuiltinTemplates", () => {
it("swaps to fresh FNote refs on frocaReloaded (protected template titles decrypt after unlock)", async () => {
// Locked protected session: the built-in template titles are the encrypted placeholder.
diff --git a/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx b/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx
index 3f7cbaef3a..22b0e55683 100644
--- a/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx
+++ b/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx
@@ -100,7 +100,7 @@ function CollectionNoteTypes({ noteId, collectionTemplates }: { noteId: string,
);
}
-function TemplateNoteTypes({ noteId, builtinTemplates }: { noteId: string, builtinTemplates: FNote[] }) {
+export function TemplateNoteTypes({ noteId, builtinTemplates }: { noteId: string, builtinTemplates: FNote[] }) {
const [ userTemplates, setUserTemplates ] = useState<FNote[]>([]);
async function refreshTemplates() {
diff --git a/apps/server/src/services/import/onenote/graph.spec.ts b/apps/server/src/services/import/onenote/graph.spec.ts
index 52b602d7a1..1782443153 100644
--- a/apps/server/src/services/import/onenote/graph.spec.ts
+++ b/apps/server/src/services/import/onenote/graph.spec.ts
@@ -1,6 +1,16 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
-import { backoffDelayMs, extractGraphErrorDetail } from "./graph.js";
+vi.mock("../../safe_fetch.js", () => ({ safeFetch: vi.fn() }));
+
+import { safeFetch } from "../../safe_fetch.js";
+import { backoffDelayMs, extractGraphErrorDetail, getAccount, getPageContent, getResource, listPages } from "./graph.js";
+
+const safeFetchMock = vi.mocked(safeFetch);
+
+/** Builds a Graph HTTP response as the mocked safeFetch returns it. */
+function graphResponse(status: number, body: string): Awaited<ReturnType<typeof safeFetch>> {
+ return new Response(body, { status }) as unknown as Awaited<ReturnType<typeof safeFetch>>;
+}
describe("backoffDelayMs", () => {
it("doubles the delay with each attempt", () => {
@@ -15,6 +25,71 @@ describe("backoffDelayMs", () => {
});
});
+describe("failed Graph requests", () => {
+ afterEach(() => {
+ safeFetchMock.mockReset();
+ });
+
+ it("reports status, Graph error detail and the failing URL for page content", async () => {
+ safeFetchMock.mockResolvedValue(graphResponse(404, JSON.stringify({
+ error: { code: "20102", message: "The specified resource ID does not exist." }
+ })));
+
+ await expect(getPageContent("token", "page-1")).rejects.toThrow(
+ "Failed to fetch OneNote page content (HTTP 404: 20102: The specified resource ID does not exist.) "
+ + "from https://graph.microsoft.com/v1.0/me/onenote/pages/page-1/content?includeInkML=true"
+ );
+ });
+
+ it("omits the detail when the body is not a Graph error envelope (resource download)", async () => {
+ safeFetchMock.mockResolvedValue(graphResponse(500, "<html>Internal Server Error</html>"));
+
+ const url = "https://graph.microsoft.com/v1.0/me/onenote/resources/res-1/$value";
+ await expect(getResource("token", url)).rejects.toThrow(
+ `Failed to fetch OneNote resource (HTTP 500) from ${url}`
+ );
+ });
+
+ it("reports the failing URL for a plain Graph GET", async () => {
+ safeFetchMock.mockResolvedValue(graphResponse(403, JSON.stringify({
+ error: { code: "AccessDenied", message: "Insufficient privileges." }
+ })));
+
+ await expect(getAccount("token")).rejects.toThrow(
+ "Microsoft Graph request failed (HTTP 403: AccessDenied: Insufficient privileges.) "
+ + "from https://graph.microsoft.com/v1.0/me"
+ );
+ });
+
+ it("names the failing @odata.nextLink, not the original URL, when a follow-up page fails", async () => {
+ // 410 rather than 429/503 so graphFetch fails immediately instead of entering backoff retries.
+ const nextLink = "https://graph.microsoft.com/v1.0/me/onenote/sections/sec-1/pages?$skip=20";
+ safeFetchMock
+ .mockResolvedValueOnce(graphResponse(200, JSON.stringify({
+ value: [{ id: "p1", title: "First" }],
+ "@odata.nextLink": nextLink
+ })))
+ .mockResolvedValueOnce(graphResponse(410, JSON.stringify({ error: { code: "Gone" } })));
+
+ await expect(listPages("token", "sec-1")).rejects.toThrow(
+ `Microsoft Graph request failed (HTTP 410: Gone) from ${nextLink}`
+ );
+ });
+
+ it("still reports status and URL when the error body cannot be read", async () => {
+ safeFetchMock.mockResolvedValue({
+ ok: false,
+ status: 502,
+ text: () => Promise.reject(new Error("connection reset"))
+ } as unknown as Awaited<ReturnType<typeof safeFetch>>);
+
+ const url = "https://graph.microsoft.com/v1.0/me/onenote/resources/res-2/$value";
+ await expect(getResource("token", url)).rejects.toThrow(
+ `Failed to fetch OneNote resource (HTTP 502) from ${url}`
+ );
+ });
+});
+
describe("extractGraphErrorDetail", () => {
it("extracts code and message from Graph's error envelope", () => {
expect(extractGraphErrorDetail(JSON.stringify({ error: { code: "20102", message: "The specified resource ID does not exist." } })))
diff --git a/apps/server/src/services/open_id.spec.ts b/apps/server/src/services/open_id.spec.ts
index e52f083261..20639ebfab 100644
--- a/apps/server/src/services/open_id.spec.ts
+++ b/apps/server/src/services/open_id.spec.ts
@@ -718,6 +718,21 @@ describe("createReactiveOidcMiddleware", () => {
expect(req.session.ssoConnectionFailed).toBeTruthy();
});
+ it("falls back to a generic detail when the thrown value stringifies to nothing", async () => {
+ const t = setup();
+ t.setConfigured(true);
+ // A thrown empty string reaches failRoundTrip through the init catch (the round-trip wrapper
+ // treats falsy as "no error"). describeError yields null and String() yields "" for it, so
+ // only the final fallback keeps the session marker non-empty — and its presence is what marks
+ // the failure downstream.
+ t.isRpInitiatedLogoutSupported.mockRejectedValueOnce("");
+
+ const { req, redirect } = await run(t.middleware);
+
+ expect(redirect).toHaveBeenCalledWith("/");
+ expect(req.session.ssoConnectionFailed).toBe("unknown error");
+ });
+
// This middleware is mounted ahead of every route, so a failed lazy init is reached by ordinary
// traffic too. Redirecting those would hand an XHR a 302 to HTML where it expects JSON, so only the
// provider round-trip — a full-page navigation — is answered that way.