Skip to content

Build your personal knowledge base with Trilium Notes

test(web-clipper): cover every line and branch, and hold it at 100%

Elian Doran397f6ba717c3
diff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.ts
index 40a90e0e99..88f02ad7e6 100644
--- a/apps/web-clipper/entrypoints/background/index.spec.ts
+++ b/apps/web-clipper/entrypoints/background/index.spec.ts
@@ -199,8 +199,36 @@ describe("background", () => {
});
});
+ it("counts an image the browser cannot read as not downloaded", async () => {
+ vi.stubGlobal("FileReader", class {
+
+ result = null;
+ onloadend: (() => void) | null = null;
+
+ readAsDataURL() {
+ setTimeout(() => this.onloadend?.());
+ }
+
+ });
+ tabMessageHandler = () => ({
+ title: "Page",
+ content: `<img src="i1">`,
+ images: [ { imageId: "i1", src: "https://example.com/a.png" } ]
+ });
+
+ await onContextMenuClicked({ menuItemId: "trilium-save-selection" });
+
+ expect(lastPayload()).toMatchObject({ content: `<img src="https://example.com/a.png">`, images: [] });
+ expect(await lastToast()).toMatchObject({
+ message: "Selection has been saved to Trilium, but 1 image could not be downloaded."
+ });
+ });
+
it("is bound to the keyboard shortcut and shows why saving failed", async () => {
tabMessageHandler = () => ({ title: "Page", content: "x" });
+ await onCommand("saveSelection");
+ expect(await lastToast()).toMatchObject({ message: "Selection has been saved to Trilium." });
+
facade.callService.mockRejectedValue(TRILIUM_FAILURE);
await onCommand("saveSelection");
diff --git a/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts b/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts
index e4acad173b..38714c4b8f 100644
--- a/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts
+++ b/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts
@@ -26,6 +26,7 @@ describe("TriliumServerFacade", () => {
vi.clearAllTimers();
vi.useRealTimers();
vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
vi.restoreAllMocks();
});
@@ -42,6 +43,15 @@ describe("TriliumServerFacade", () => {
]);
});
+ it("looks for a production desktop app on its own port", async () => {
+ vi.stubEnv("DEV", false);
+ fetchMock.mockResolvedValue(handshake("1.0"));
+
+ await createFacade();
+
+ expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:37840/api/clipper/handshake");
+ });
+
it("uses the configured desktop port and searches again every minute", async () => {
await fakeBrowser.storage.sync.set({ triliumDesktopPort: "12345" });
fetchMock.mockResolvedValue(handshake("1.2"));
@@ -87,9 +97,13 @@ describe("TriliumServerFacade", () => {
it("reports not-found when neither the desktop app nor the server is Trilium", async () => {
await fakeBrowser.storage.sync.set(SERVER);
- fetchMock.mockResolvedValue(new Response(JSON.stringify({ appName: "other" })));
+ fetchMock.mockImplementation(async () => Response.json({ appName: "other" }));
await createFacade();
expect(lastSearchStatus()).toEqual({ status: "not-found" });
+ expect(fetchMock).toHaveBeenLastCalledWith(
+ "https://trilium.example/api/clipper/handshake", { headers: { Authorization: "secret" } });
+ expect(console.log).not.toHaveBeenCalledWith(
+ "Request to the configured server instance failed with:", expect.anything());
fetchMock.mockReset();
fetchMock.mockImplementation(async (url) => {
@@ -172,6 +186,9 @@ describe("TriliumServerFacade", () => {
fetchMock.mockRejectedValue(new Error("connection reset"));
await expect(openNote()).rejects.toThrow(requestFailed("connection reset"));
+
+ fetchMock.mockRejectedValue("offline");
+ await expect(openNote()).rejects.toThrow(requestFailed("offline"));
});
it("waits for a running search and rejects once Trilium is not found", async () => {
@@ -195,15 +212,22 @@ describe("TriliumServerFacade", () => {
.rejects.toThrow(expect.objectContaining({ reason: "not-found" }));
});
- it("rejects while Trilium has a different protocol version", async () => {
+ it("rejects while Trilium has a different protocol version, naming the side to update", async () => {
fetchMock.mockResolvedValue(handshake("0.9"));
const facade = await createFacade();
const call = facade.callService("GET", "notes-by-url/x");
await expect(call).rejects.toBeInstanceOf(TriliumError);
- await expect(call)
- .rejects.toThrow(expect.objectContaining({ reason: "version-mismatch" }));
+ await expect(call).rejects.toThrow(expect.objectContaining({
+ reason: "version-mismatch",
+ message: expect.stringContaining("Update Trilium to the latest version.")
+ }));
expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ fetchMock.mockResolvedValue(handshake("2.0"));
+ await facade.triggerSearchForTrilium();
+ await expect(facade.callService("GET", "notes-by-url/x")).rejects.toThrow(
+ expect.objectContaining({ message: expect.stringContaining("Update the web clipper") }));
});
});
diff --git a/apps/web-clipper/entrypoints/background/trilium_server_facade.ts b/apps/web-clipper/entrypoints/background/trilium_server_facade.ts
index 821ee23c58..74da9190d0 100644
--- a/apps/web-clipper/entrypoints/background/trilium_server_facade.ts
+++ b/apps/web-clipper/entrypoints/background/trilium_server_facade.ts
@@ -18,6 +18,8 @@ export type TriliumSearchStatus = {
triliumMajor: number;
};
+type FoundStatus = Exclude<TriliumSearchStatus, { status: "searching" | "not-found" }>;
+
export type TriliumSearchNoteStatus = {
status: "not-found",
noteId: null
@@ -39,7 +41,7 @@ export class TriliumError extends Error {
}
export default class TriliumServerFacade {
- private triliumSearch?: TriliumSearchStatus;
+ private triliumSearch: TriliumSearchStatus = { status: "searching" };
private triliumSearchNote?: TriliumSearchNoteStatus;
constructor() {
@@ -183,15 +185,17 @@ export default class TriliumServerFacade {
}
this.setTriliumSearchNote(newStatus);
}
+ /** Resolves with the outcome of the running search, and rejects if Trilium was not found. */
async waitForTriliumSearch() {
- return new Promise<void>((res, rej) => {
+ return new Promise<FoundStatus>((res, rej) => {
const checkStatus = () => {
- if (this.triliumSearch?.status === "searching") {
+ const search = this.triliumSearch;
+ if (search.status === "searching") {
setTimeout(checkStatus, 500);
- } else if (this.triliumSearch?.status === 'not-found') {
+ } else if (search.status === "not-found") {
rej(notFound());
} else {
- res();
+ res(search);
}
};
@@ -210,17 +214,13 @@ export default class TriliumServerFacade {
}
async callService(method: string, path: string, body?: string | object) {
- await this.waitForTriliumSearch();
- const search = this.triliumSearch;
- if (search?.status === "version-mismatch") {
+ const search = await this.waitForTriliumSearch();
+ if (search.status === "version-mismatch") {
const { extensionMajor, triliumMajor } = search;
const outdated = extensionMajor > triliumMajor ? "Trilium" : "the web clipper";
throw new TriliumError("version-mismatch", "This version of the web clipper does not "
+ `work with this version of Trilium. Update ${outdated} to the latest version.`);
}
- if (search?.status !== "found-desktop" && search?.status !== "found-server") {
- throw notFound();
- }
let response: Response;
try {
diff --git a/apps/web-clipper/entrypoints/content/index.spec.ts b/apps/web-clipper/entrypoints/content/index.spec.ts
index 25af1f108d..0eb313541e 100644
--- a/apps/web-clipper/entrypoints/content/index.spec.ts
+++ b/apps/web-clipper/entrypoints/content/index.spec.ts
@@ -88,9 +88,12 @@ describe("content script", () => {
it("falls back to the document title and fails without a selection", async () => {
document.head.innerHTML = "";
- document.title = " Fallback ";
document.body.innerHTML = "<p id=\"p\">Text</p>";
selectRange("p", "p");
+ expect(document.getElementsByTagName("title")).toHaveLength(0);
+ expect(await send({ name: "trilium-save-selection" })).toMatchObject({ title: "" });
+
+ document.title = " Fallback ";
expect(await send({ name: "trilium-save-selection" }))
.toMatchObject({ title: "Fallback" });
diff --git a/apps/web-clipper/entrypoints/options/options.spec.tsx b/apps/web-clipper/entrypoints/options/options.spec.tsx
index 5fd9b7411e..e7ea25ede0 100644
--- a/apps/web-clipper/entrypoints/options/options.spec.tsx
+++ b/apps/web-clipper/entrypoints/options/options.spec.tsx
@@ -88,6 +88,37 @@ describe("options page", () => {
expect(container.querySelector("input[type=password]")).not.toBeNull();
});
+ it("explains why the login failed", async () => {
+ await renderOptions();
+ await type("input[type=text]:not(#trilium-desktop-port)", "https://trilium.example");
+ await type("input[type=password]", "wrong");
+
+ fetchMock.mockResolvedValueOnce(Response.json({ message: "Incorrect credential", factor: "password" }, { status: 401 }));
+ await submit(1);
+ expect(message()).toEqual({ className: "message message-error", text: "Incorrect credentials." });
+
+ fetchMock.mockResolvedValueOnce(new Response("", { status: 502 }));
+ await submit(1);
+ expect(message()?.text).toBe("Unrecognised response with status code 502");
+
+ fetchMock.mockRejectedValueOnce(new TypeError("Failed to fetch"));
+ await submit(1);
+ expect(message()?.text).toBe("Unknown error: Failed to fetch");
+ expect(await stored("authToken")).toBeUndefined();
+ });
+
+ it("renders itself into the page's root element", async () => {
+ const root = document.createElement("div");
+ root.id = "root";
+ document.body.appendChild(root);
+ vi.resetModules();
+
+ await import("./main");
+
+ expect(root.querySelector(".options")).not.toBeNull();
+ root.remove();
+ });
+
it("shows the configured server, which needs both an address and a token", async () => {
await browser.storage.sync.set({ triliumServerUrl: "https://trilium.example", authToken: "" });
await renderOptions();
@@ -123,6 +154,9 @@ describe("requestToken", () => {
fetchMock.mockRejectedValueOnce(new TypeError("Failed to fetch"));
expect(await requestToken("https://s", "p", "")).toEqual({ kind: "network-error", message: "Failed to fetch" });
+
+ fetchMock.mockRejectedValueOnce("offline");
+ expect(await requestToken("https://s", "p", "")).toEqual({ kind: "network-error", message: "offline" });
});
});
diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
index 0d8beeec1f..9830afea3d 100644
--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx
+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx
@@ -26,6 +26,7 @@ describe("popup", () => {
await act(() => render(null, container));
container.remove();
vi.clearAllMocks();
+ vi.unstubAllGlobals();
vi.restoreAllMocks();
});
@@ -62,9 +63,18 @@ describe("popup", () => {
expect(container.querySelector(".status-warning")?.textContent).toContain("Please update Trilium Notes");
expect(captureButtons().every((button) => !button.disabled)).toBe(true);
+ await receive({
+ name: "trilium-search-status",
+ triliumSearch: { status: "version-mismatch", extensionMajor: 1, triliumMajor: 2 }
+ });
+ expect(container.querySelector(".status-warning")?.textContent).toContain("Please update this extension");
+
await receive({ name: "trilium-search-status", triliumSearch: { status: "searching" } });
expect(statusText()).toBe("searching");
expect(captureButtons().every((button) => button.disabled)).toBe(true);
+
+ await receive({ name: "unrelated" });
+ expect(statusText()).toBe("searching");
});
it("offers to open a page that was already clipped", async () => {
@@ -95,6 +105,63 @@ describe("popup", () => {
await click("Options");
expect(openOptionsPage).toHaveBeenCalledOnce();
expect(closeWindow).toHaveBeenCalledTimes(2);
+
+ const openWindow = vi.spyOn(window, "open").mockImplementation(() => null);
+ await click("Help");
+ expect(openWindow).toHaveBeenCalledWith("https://docs.triliumnotes.org/user-guide/setup/web-clipper", "_blank");
+ });
+
+ it("tells the user when the background script cannot be reached", async () => {
+ const alertMock = vi.fn();
+ vi.stubGlobal("alert", alertMock);
+ sendMessage.mockRejectedValueOnce(new Error("Receiving end does not exist."));
+
+ await click("Save whole page");
+
+ expect(alertMock).toHaveBeenCalledWith("Calling browser runtime failed. Refreshing page might help.");
+ });
+
+ it("keeps the note open when it could not be saved, and keeps the page title on request", async () => {
+ await click("Save link with a note");
+ const textArea = container.querySelector("textarea");
+ const keepTitle = container.querySelector<HTMLInputElement>("input[type=checkbox]");
+ expect(textArea).not.toBeNull();
+ expect(keepTitle?.checked).toBe(false);
+
+ await act(() => {
+ if (!textArea || !keepTitle) return;
+ textArea.value = "First. Second.";
+ textArea.dispatchEvent(new Event("input", { bubbles: true }));
+ keepTitle.click();
+ });
+ expect(keepTitle?.checked).toBe(true);
+
+ await act(async () => {
+ textArea?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
+ });
+ expect(sendMessage).not.toHaveBeenCalledWith(expect.objectContaining({ name: "save-link-with-note" }));
+
+ sendMessage.mockResolvedValueOnce(undefined);
+ await click("Save");
+ expect(sendMessage).toHaveBeenCalledWith({
+ name: "save-link-with-note",
+ title: "",
+ content: "<p>First. Second.</p>"
+ });
+ expect(textArea?.value).toBe("First. Second.");
+ expect(closeWindow).not.toHaveBeenCalled();
+ });
+
+ it("renders itself into the page's root element", async () => {
+ const root = document.createElement("div");
+ root.id = "root";
+ document.body.appendChild(root);
+ vi.resetModules();
+
+ await import("./main");
+
+ expect(root.querySelector(".popup")).not.toBeNull();
+ root.remove();
});
it("saves a link with a note on Ctrl+Enter, and cancels it", async () => {
diff --git a/apps/web-clipper/vitest.config.mts b/apps/web-clipper/vitest.config.mts
index 46b85f621a..7cd4ed13a9 100644
--- a/apps/web-clipper/vitest.config.mts
+++ b/apps/web-clipper/vitest.config.mts
@@ -25,10 +25,10 @@ export default defineConfig({
// `entrypoints/…/index.ts` to another project of the monorepo.
reporter: [ "text", [ "lcov", { projectRoot: join(import.meta.dirname, "../..") } ] ],
thresholds: {
- lines: 95,
- statements: 95,
- functions: 95,
- branches: 90
+ lines: 100,
+ statements: 100,
+ functions: 100,
+ branches: 100
}
}
}