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): cover import/markdown/spreadsheet business logic
Elian Doran26816c534f51
diff --git a/apps/client/src/services/import.spec.ts b/apps/client/src/services/import.spec.tsindex d067c8849c..c0453d7395 100644--- a/apps/client/src/services/import.spec.ts+++ b/apps/client/src/services/import.spec.ts@@ -151,6 +151,15 @@ describe("importNotes ws handler", () => {expect(toastService.showError).toHaveBeenCalledWith("nope");});+ it("shows the error only once when the same task reports it twice (the WebSocket + fallback dedup)", async () => {+ // A fresh taskId — the dedup guard is module-level state that survives clearAllMocks.+ await handler()({ type: "taskError", taskType: "importNotes", taskId: "dedupT", message: "boom" } as any);+ await handler()({ type: "taskError", taskType: "importNotes", taskId: "dedupT", message: "boom again" } as any);+ // The second report for the same taskId is suppressed, so only the first toast shows.+ expect(toastService.showError).toHaveBeenCalledTimes(1);+ expect(toastService.showError).toHaveBeenCalledWith("boom");+ });+it("shows a persistent count-only progress toast when no total is reported", async () => {await handler()({ type: "taskProgressCount", taskType: "importNotes", taskId: "t2", progressCount: 3 } as any);expect(toastService.showPersistent).toHaveBeenCalledTimes(1);diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts b/apps/client/src/widgets/type_widgets/markdown/completions.spec.tsindex 465fcacf80..1e5c57a2a0 100644--- a/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts+++ b/apps/client/src/widgets/type_widgets/markdown/completions.spec.ts@@ -1,9 +1,12 @@+import type { CompletionContext } from "@codemirror/autocomplete";import { markdown } from "@codemirror/lang-markdown";import { ensureSyntaxTree } from "@codemirror/language";import { EditorState } from "@codemirror/state";-import { describe, expect, it } from "vitest";+import type { MimeType } from "@triliumnext/commons";+import { afterEach, describe, expect, it, vi } from "vitest";-import { buildTaskItemInsert, isClosingFence, parseCodeFencePrefix } from "./completions.js";+import mime_types from "../../../services/mime_types.js";+import { buildCodeFenceOptions, buildTaskItemInsert, codeFenceCompletionSource, isClosingFence, parseCodeFencePrefix } from "./completions.js";describe("buildTaskItemInsert", () => {it("prepends a bullet when not already in a list item", () => {@@ -76,3 +79,61 @@ describe("isClosingFence", () => {expect(lineStart("```js\ncode\n```", 3)).toBe(11);});});++describe("buildCodeFenceOptions", () => {+ afterEach(() => vi.restoreAllMocks());++ const mime = (over: Partial<MimeType>): MimeType => ({+ title: "T", mime: "text/x", enabled: true, mdLanguageCode: "x", ...over+ } as MimeType);++ it("emits one option per enabled language, skipping disabled, code-less and duplicate entries", () => {+ vi.spyOn(mime_types, "getMimeTypes").mockReturnValue([+ mime({ mdLanguageCode: "js", title: "JavaScript" }),+ mime({ mdLanguageCode: "py", title: "Python", enabled: false }), // disabled → skipped+ mime({ mdLanguageCode: undefined, title: "No code" }), // no language code → skipped+ mime({ mdLanguageCode: "js", title: "JS again" }) // duplicate code → skipped+ ]);++ expect(buildCodeFenceOptions()).toEqual([{ label: "js", detail: "JavaScript" }]);+ });+});++describe("codeFenceCompletionSource", () => {+ afterEach(() => vi.restoreAllMocks());++ function context(doc: string, pos: number): CompletionContext {+ const state = EditorState.create({ doc, extensions: [ markdown() ] });+ ensureSyntaxTree(state, doc.length);+ return { state, pos } as CompletionContext;+ }++ function withLanguages(...codes: string[]) {+ vi.spyOn(mime_types, "getMimeTypes").mockReturnValue(+ codes.map((code) => ({ title: code, mime: `text/${code}`, enabled: true, mdLanguageCode: code }) as MimeType)+ );+ }++ it("offers the enabled languages right after a fence opener, anchored at the language token", () => {+ withLanguages("js", "py");+ const result = codeFenceCompletionSource(context("```", 3));+ expect(result?.from).toBe(3); // line.from (0) + langStart (3)+ expect(result?.options.map((o) => o.label)).toEqual([ "js", "py" ]);+ });++ it("returns null when the line is not a fence opener", () => {+ withLanguages("js");+ expect(codeFenceCompletionSource(context("plain text", 5))).toBeNull();+ });++ it("returns null on a closing fence, so only openers get language completions", () => {+ withLanguages("js");+ // Cursor on the terminating ``` of `\`\`\`js\ncode\n\`\`\`` — line 3 starts at offset 11.+ expect(codeFenceCompletionSource(context("```js\ncode\n```", 14))).toBeNull();+ });++ it("returns null on a valid opener when no languages are enabled", () => {+ withLanguages(); // none enabled → no options+ expect(codeFenceCompletionSource(context("```", 3))).toBeNull();+ });+});diff --git a/apps/client/src/widgets/type_widgets/markdown/completions.ts b/apps/client/src/widgets/type_widgets/markdown/completions.tsindex c4789c4485..fba68737eb 100644--- a/apps/client/src/widgets/type_widgets/markdown/completions.ts+++ b/apps/client/src/widgets/type_widgets/markdown/completions.ts@@ -282,7 +282,7 @@ export function isClosingFence(state: EditorState, lineFrom: number): boolean {}/** Builds the fence-language completions from the user's enabled code-note languages. */-function buildCodeFenceOptions(): Completion[] {+export function buildCodeFenceOptions(): Completion[] {const seen = new Set<string>();const options: Completion[] = [];for (const mimeType of mime_types.getMimeTypes()) {@@ -298,7 +298,7 @@ function buildCodeFenceOptions(): Completion[] {* Completion source for code-fence languages: triggers only right after a ``` fence opener and lists* the user's enabled languages. Returns `null` everywhere else, so it never pollutes the slash menu.*/-function codeFenceCompletionSource(context: CompletionContext): CompletionResult | null {+export function codeFenceCompletionSource(context: CompletionContext): CompletionResult | null {const line = context.state.doc.lineAt(context.pos);const parsed = parseCodeFencePrefix(line.text.slice(0, context.pos - line.from));if (!parsed || isClosingFence(context.state, line.from)) return null;diff --git a/apps/client/src/widgets/type_widgets/markdown/editor_utils.spec.ts b/apps/client/src/widgets/type_widgets/markdown/editor_utils.spec.tsnew file mode 100644index 0000000000..e38fc4acc8--- /dev/null+++ b/apps/client/src/widgets/type_widgets/markdown/editor_utils.spec.ts@@ -0,0 +1,121 @@+import type VanillaCodeMirror from "@triliumnext/codemirror";+import { beforeEach, describe, expect, it, vi } from "vitest";++import type FNote from "../../../entities/fnote";+import { t } from "../../../services/i18n.js";+import server from "../../../services/server.js";+import toast from "../../../services/toast.js";+import { insertText, replaceSelection, uploadImageAndInsert } from "./editor_utils.js";++// A minimal CodeMirror view stand-in: the helpers only read the cursor head and+// call dispatch(), so we capture the dispatched transaction to assert against it.+function makeView(head = 0) {+ return {+ state: { selection: { main: { head } } },+ dispatch: vi.fn()+ } as unknown as VanillaCodeMirror;+}++const note = { noteId: "note123" } as FNote;+const file = new File([ "x" ], "picture.png", { type: "image/png" });++const uploadMock = vi.fn();+const showErrorMock = vi.fn();++beforeEach(() => {+ vi.clearAllMocks();+ server.upload = uploadMock as typeof server.upload;+ toast.showError = showErrorMock as typeof toast.showError;+});++describe("insertText", () => {+ it("inserts at an explicit position and moves the cursor to the end of the inserted text", () => {+ const view = makeView();+ insertText(view, "hello", 3);+ expect(view.dispatch).toHaveBeenCalledWith({+ changes: { from: 3, insert: "hello" },+ selection: { anchor: 8 }+ });+ });++ it("falls back to the current cursor head when no position is given", () => {+ const view = makeView(10);+ insertText(view, "ab");+ expect(view.dispatch).toHaveBeenCalledWith({+ changes: { from: 10, insert: "ab" },+ selection: { anchor: 12 }+ });+ });+});++describe("replaceSelection", () => {+ it("replaces the range with text and moves the cursor to the end", () => {+ const view = makeView();+ replaceSelection(view, "new", 4, 9);+ expect(view.dispatch).toHaveBeenCalledWith({+ changes: { from: 4, to: 9, insert: "new" },+ selection: { anchor: 7 }+ });+ });+});++describe("uploadImageAndInsert", () => {+ it("inserts a markdown image reference on a successful upload and shows no error", async () => {+ const view = makeView(5);+ uploadMock.mockResolvedValue({ uploaded: true, url: "/img/abc.png" });++ await uploadImageAndInsert(view, note, file, 5);++ expect(uploadMock).toHaveBeenCalledWith("notes/note123/attachments/upload", file, undefined, "POST");+ const markdownRef = "";+ expect(view.dispatch).toHaveBeenCalledWith({+ changes: { from: 5, insert: markdownRef },+ selection: { anchor: 5 + markdownRef.length }+ });+ expect(showErrorMock).not.toHaveBeenCalled();+ });++ it("surfaces the server's message (and inserts nothing) when the upload reports failure", async () => {+ const view = makeView();+ uploadMock.mockResolvedValue({ uploaded: false, message: "Disk full" });++ await uploadImageAndInsert(view, note, file);++ expect(view.dispatch).not.toHaveBeenCalled();+ expect(showErrorMock).toHaveBeenCalledTimes(1);+ // i18next is uninitialised in the test env so t() returns the key; we only+ // assert the server detail is appended to whatever base message was built.+ expect(showErrorMock).toHaveBeenCalledWith(expect.stringContaining("Disk full"));+ });++ it("falls back to a network Error's message when the upload throws", async () => {+ const view = makeView();+ uploadMock.mockRejectedValue(new Error("Network down"));++ await uploadImageAndInsert(view, note, file);++ expect(showErrorMock).toHaveBeenCalledWith(expect.stringContaining("Network down"));+ });++ it("shows the bare base message when the upload throws a non-Error value", async () => {+ const view = makeView();+ // A thrown string carries no `.message`, so no detail is appended.+ uploadMock.mockRejectedValue("just a string");++ await uploadImageAndInsert(view, note, file);++ expect(showErrorMock).toHaveBeenCalledWith(t("markdown_editor.image_upload_failed", { name: "picture.png" }));+ });++ it("shows the bare base message when no detail is available", async () => {+ const view = makeView();+ // A resolved-but-unsuccessful result carrying no message yields no detail.+ uploadMock.mockResolvedValue({ uploaded: false });++ await uploadImageAndInsert(view, note, file);++ // With no detail, the toast is exactly the base message and nothing is appended.+ expect(showErrorMock).toHaveBeenCalledWith(t("markdown_editor.image_upload_failed", { name: "picture.png" }));+ expect(showErrorMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/navigation.spec.ts b/apps/client/src/widgets/type_widgets/spreadsheet/navigation.spec.tsindex 635c3d5f7b..4834d4cf05 100644--- a/apps/client/src/widgets/type_widgets/spreadsheet/navigation.spec.ts+++ b/apps/client/src/widgets/type_widgets/spreadsheet/navigation.spec.ts@@ -1,6 +1,7 @@+import { Direction } from "@univerjs/core";import { describe, expect, it } from "vitest";-import { isOutOfBoundsMove, type SelectionBounds } from "./navigation";+import { isOutOfBoundsMove, type SelectionBounds, toNavigationDirection } from "./navigation";describe("isOutOfBoundsMove", () => {// A 10x10 sheet (rows/columns 0..9) with the selection on a single, interior cell.@@ -51,3 +52,18 @@ describe("isOutOfBoundsMove", () => {expect(isOutOfBoundsMove("up", bottomRange)).toBe(false);});});++describe("toNavigationDirection", () => {+ it("maps each Univer arrow direction to its lowercase string", () => {+ expect(toNavigationDirection(Direction.UP)).toBe("up");+ expect(toNavigationDirection(Direction.DOWN)).toBe("down");+ expect(toNavigationDirection(Direction.LEFT)).toBe("left");+ expect(toNavigationDirection(Direction.RIGHT)).toBe("right");+ });++ it("returns undefined for any non-arrow direction", () => {+ // Univer's Direction enum carries non-arrow members (and future values); anything+ // outside the four arrows isn't a cell move, so it must not clamp.+ expect(toNavigationDirection(99 as Direction)).toBeUndefined();+ });+});diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/navigation.ts b/apps/client/src/widgets/type_widgets/spreadsheet/navigation.tsindex 9f9aaafd7d..806813b1a5 100644--- a/apps/client/src/widgets/type_widgets/spreadsheet/navigation.ts+++ b/apps/client/src/widgets/type_widgets/spreadsheet/navigation.ts@@ -92,7 +92,7 @@ export default function useClampEdgeNavigation(apiRef: MutableRef<FUniver | unde}, [ apiRef ]);}-function toNavigationDirection(direction: Direction): NavigationDirection | undefined {+export function toNavigationDirection(direction: Direction): NavigationDirection | undefined {switch (direction) {case Direction.UP:return "up";