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(server): basic coverage of some core routes
Elian Doranc35efc66c0a5
diff --git a/apps/server/spec/support/internal_api.ts b/apps/server/spec/support/internal_api.tsnew file mode 100644index 0000000000..3d9960c4a1--- /dev/null+++ b/apps/server/spec/support/internal_api.ts@@ -0,0 +1,76 @@+import type { Application } from "express";+import supertest from "supertest";+import { expect } from "vitest";++export type ApiAgent = ReturnType<typeof supertest.agent>;++export interface ApiTestContext {+ app: Application;+ agent: ApiAgent;+ /**+ * CSRF token that must be set as the `x-csrf-token` header on mutating+ * (POST/PUT/PATCH/DELETE) requests.+ */+ csrfToken: string;+}++/**+ * Boots the full server Express app against the in-memory demo fixture DB and+ * performs the browser login handshake, returning an authenticated supertest+ * agent plus a CSRF token.+ *+ * Mirrors `apps/server/src/routes/api/options.spec.ts`: `POST /login`+ * establishes the session cookie, `GET /bootstrap` issues the CSRF cookie and+ * token. The agent persists both cookies across subsequent requests. CSRF uses+ * the double-submit pattern, so GET/HEAD/OPTIONS need no token; only mutating+ * verbs do.+ *+ * Each spec file runs in its own vitest fork (`pool: "forks"`) with a fresh+ * in-memory copy of the fixture, so mutations don't leak across files — call+ * this once per file in `beforeAll()`.+ */+export async function bootLoggedInApp(): Promise<ApiTestContext> {+ const buildApp = (await import("../../src/app.js")).default;+ const app = await buildApp();+ const agent = supertest.agent(app);++ await agent.post("/login").send({ password: "demo1234" }).expect(302);++ const boot = await agent.get("/bootstrap").expect(200);+ const csrfToken = boot.body.csrfToken as string;+ expect(csrfToken).toBeTruthy();++ return { app, agent, csrfToken };+}++export interface CreatedNote {+ noteId: string;+ branchId: string;+}++interface CreateNoteOptions {+ parentNoteId?: string;+ title?: string;+ content?: string;+}++/**+ * Creates a disposable child note through the internal API and returns its+ * `{ noteId, branchId }`. Lets tests operate on a known note without coupling+ * to specific fixture content.+ */+export async function createTextNote(+ { agent, csrfToken }: ApiTestContext,+ { parentNoteId = "root", title = "Test note", content = "<p>hello</p>" }: CreateNoteOptions = {}+): Promise<CreatedNote> {+ const res = await agent+ .post(`/api/notes/${parentNoteId}/children?target=into`)+ .set("x-csrf-token", csrfToken)+ .send({ title, type: "text", content })+ .expect(200);++ return {+ noteId: res.body.note.noteId as string,+ branchId: res.body.branch.branchId as string+ };+}diff --git a/apps/server/src/routes/api/attributes.spec.ts b/apps/server/src/routes/api/attributes.spec.tsnew file mode 100644index 0000000000..dec66bd0af--- /dev/null+++ b/apps/server/src/routes/api/attributes.spec.ts@@ -0,0 +1,104 @@+import { beforeAll, describe, expect, it } from "vitest";++import {+ type ApiTestContext,+ bootLoggedInApp,+ createTextNote } from "../../../spec/support/internal_api.js";++let ctx: ApiTestContext;++interface AttrRow {+ attributeId: string;+ type: string;+ name: string;+ value: string;+}++describe("Attributes API", () => {+ beforeAll(async () => {+ ctx = await bootLoggedInApp();+ });++ describe("reading", () => {+ it("returns the effective attributes of a note", async () => {+ const res = await ctx.agent.get("/api/notes/_hidden/attributes").expect(200);+ const attrs = res.body as AttrRow[];+ expect(Array.isArray(attrs)).toBe(true);+ expect(attrs.some((a) => a.name === "docName")).toBe(true);+ });++ it("returns attribute names filtered by type and query", async () => {+ const res = await ctx.agent+ .get("/api/attribute-names")+ .query({ type: "label", query: "" })+ .expect(200);+ expect(Array.isArray(res.body)).toBe(true);+ });++ it("400s when type/query params are missing", async () => {+ await ctx.agent.get("/api/attribute-names").expect(400);+ });++ it("returns distinct values for an attribute name", async () => {+ const res = await ctx.agent.get("/api/attribute-values/docName").expect(200);+ expect(Array.isArray(res.body)).toBe(true);+ });+ });++ describe("writing", () => {+ it("adds a label, reads it back, then deletes it", async () => {+ const { noteId } = await createTextNote(ctx);++ await ctx.agent+ .post(`/api/notes/${noteId}/attributes`)+ .set("x-csrf-token", ctx.csrfToken)+ .send({ type: "label", name: "myLabel", value: "myValue" })+ .expect(204);++ const afterAdd = await ctx.agent.get(`/api/notes/${noteId}/attributes`).expect(200);+ const added = (afterAdd.body as AttrRow[]).find((a) => a.name === "myLabel");+ expect(added).toMatchObject({ type: "label", value: "myValue" });++ await ctx.agent+ .delete(`/api/notes/${noteId}/attributes/${added!.attributeId}`)+ .set("x-csrf-token", ctx.csrfToken)+ .expect(204);++ const afterDelete = await ctx.agent.get(`/api/notes/${noteId}/attributes`).expect(200);+ const remainingIds = (afterDelete.body as AttrRow[]).map((a) => a.attributeId);+ expect(remainingIds).not.toContain(added!.attributeId);+ });++ it("sets an attribute idempotently via set-attribute", async () => {+ const { noteId } = await createTextNote(ctx);++ await ctx.agent+ .put(`/api/notes/${noteId}/set-attribute`)+ .set("x-csrf-token", ctx.csrfToken)+ .send({ type: "label", name: "color", value: "red" })+ .expect(204);++ await ctx.agent+ .put(`/api/notes/${noteId}/set-attribute`)+ .set("x-csrf-token", ctx.csrfToken)+ .send({ type: "label", name: "color", value: "blue" })+ .expect(204);++ const res = await ctx.agent.get(`/api/notes/${noteId}/attributes`).expect(200);+ const colors = (res.body as AttrRow[]).filter((a) => a.name === "color");+ expect(colors).toHaveLength(1);+ expect(colors[0].value).toBe("blue");+ });++ it("creates a relation between two notes", async () => {+ const { noteId } = await createTextNote(ctx);++ const res = await ctx.agent+ .put(`/api/notes/${noteId}/relations/myRelation/to/root`)+ .set("x-csrf-token", ctx.csrfToken)+ .expect(200);++ expect(res.body).toMatchObject({ type: "relation", name: "myRelation", value: "root" });+ });+ });+});diff --git a/apps/server/src/routes/api/notes.spec.ts b/apps/server/src/routes/api/notes.spec.tsnew file mode 100644index 0000000000..4f06ade15c--- /dev/null+++ b/apps/server/src/routes/api/notes.spec.ts@@ -0,0 +1,128 @@+import { getSql } from "@triliumnext/core";+import { beforeAll, describe, expect, it } from "vitest";++import {+ type ApiTestContext,+ bootLoggedInApp,+ createTextNote } from "../../../spec/support/internal_api.js";++let ctx: ApiTestContext;++function noteIsDeleted(noteId: string): number | null {+ const row = getSql().getRowOrNull<{ isDeleted: number }>(+ "SELECT isDeleted FROM notes WHERE noteId = ?",+ [ noteId ]+ );+ return row ? row.isDeleted : null;+}++describe("Notes API", () => {+ beforeAll(async () => {+ ctx = await bootLoggedInApp();+ });++ describe("reading", () => {+ it("returns note metadata for an existing note", async () => {+ const res = await ctx.agent.get("/api/notes/root").expect(200);+ expect(res.body.noteId).toBe("root");+ expect(res.body.type).toBeTruthy();+ });++ it("returns timestamp metadata", async () => {+ const res = await ctx.agent.get("/api/notes/root/metadata").expect(200);+ expect(res.body).toMatchObject({+ dateCreated: expect.any(String),+ utcDateCreated: expect.any(String),+ dateModified: expect.any(String),+ utcDateModified: expect.any(String)+ });+ });++ it("returns the note blob", async () => {+ const res = await ctx.agent.get("/api/notes/root/blob").expect(200);+ expect(res.body.blobId).toBeTruthy();+ expect(typeof res.body.content).toBe("string");+ });++ it("404s for a missing note", async () => {+ await ctx.agent.get("/api/notes/missingNote123").expect(404);+ });+ });++ describe("creating", () => {+ it("creates a child note under root", async () => {+ const res = await ctx.agent+ .post("/api/notes/root/children?target=into")+ .set("x-csrf-token", ctx.csrfToken)+ .send({ title: "Created via API", type: "text", content: "<p>body</p>" })+ .expect(200);++ expect(res.body.note.noteId).toBeTruthy();+ expect(res.body.note.title).toBe("Created via API");+ expect(res.body.branch.parentNoteId).toBe("root");+ });++ it("400s when the target query param is invalid", async () => {+ await ctx.agent+ .post("/api/notes/root/children")+ .set("x-csrf-token", ctx.csrfToken)+ .send({ title: "no target", type: "text" })+ .expect(400);+ });+ });++ describe("updating", () => {+ it("changes a note title and returns the updated note", async () => {+ const { noteId } = await createTextNote(ctx, { title: "Before" });++ const res = await ctx.agent+ .put(`/api/notes/${noteId}/title`)+ .set("x-csrf-token", ctx.csrfToken)+ .send({ title: "After" })+ .expect(200);++ expect(res.body.title).toBe("After");+ });++ it("updates note content", async () => {+ const { noteId } = await createTextNote(ctx, { content: "<p>old</p>" });++ await ctx.agent+ .put(`/api/notes/${noteId}/data`)+ .set("x-csrf-token", ctx.csrfToken)+ .send({ content: "<p>new</p>" })+ .expect(204);++ const blob = await ctx.agent.get(`/api/notes/${noteId}/blob`).expect(200);+ expect(blob.body.content).toContain("new");+ });+ });++ describe("deleting and undeleting", () => {+ it("soft-deletes a note, then undeletes it", async () => {+ const { noteId } = await createTextNote(ctx, { title: "To delete" });+ expect(noteIsDeleted(noteId)).toBe(0);++ await ctx.agent+ .delete(`/api/notes/${noteId}`)+ .query({ taskId: "test-delete", last: "true" })+ .set("x-csrf-token", ctx.csrfToken)+ .expect(204);+ expect(noteIsDeleted(noteId)).toBe(1);++ await ctx.agent+ .put(`/api/notes/${noteId}/undelete`)+ .set("x-csrf-token", ctx.csrfToken)+ .expect(204);+ expect(noteIsDeleted(noteId)).toBe(0);+ });++ it("400s when deleting without a taskId", async () => {+ const { noteId } = await createTextNote(ctx, { title: "Needs taskId" });+ await ctx.agent+ .delete(`/api/notes/${noteId}`)+ .set("x-csrf-token", ctx.csrfToken)+ .expect(400);+ });+ });+});diff --git a/apps/server/src/routes/api/search.spec.ts b/apps/server/src/routes/api/search.spec.tsnew file mode 100644index 0000000000..171a9605e4--- /dev/null+++ b/apps/server/src/routes/api/search.spec.ts@@ -0,0 +1,50 @@+import { beforeAll, describe, expect, it } from "vitest";++import {+ type ApiTestContext,+ bootLoggedInApp,+ createTextNote } from "../../../spec/support/internal_api.js";++let ctx: ApiTestContext;+const UNIQUE_TOKEN = "ZzUniqueSearchTokenQwerty";++describe("Search API", () => {+ let createdNoteId: string;++ beforeAll(async () => {+ ctx = await bootLoggedInApp();+ ({ noteId: createdNoteId } = await createTextNote(ctx, { title: UNIQUE_TOKEN }));+ });++ it("returns matching note ids for a full search", async () => {+ const res = await ctx.agent.get(`/api/search/${UNIQUE_TOKEN}`).expect(200);+ expect(Array.isArray(res.body)).toBe(true);+ expect(res.body).toContain(createdNoteId);+ });++ it("returns structured quick-search results with snippets", async () => {+ const res = await ctx.agent.get(`/api/quick-search/${UNIQUE_TOKEN}`).expect(200);+ expect(res.body.searchResultNoteIds).toContain(createdNoteId);+ expect(Array.isArray(res.body.searchResults)).toBe(true);+ });++ it("lists template note ids", async () => {+ const res = await ctx.agent.get("/api/search-templates").expect(200);+ expect(Array.isArray(res.body)).toBe(true);+ });++ it("400s when searching from a note that is not a search note", async () => {+ await ctx.agent.get("/api/search-note/root").expect(400);+ });++ it("returns related notes for an attribute query", async () => {+ const res = await ctx.agent+ .post("/api/search-related")+ .set("x-csrf-token", ctx.csrfToken)+ .send({ type: "label", name: "docName", value: "hidden" })+ .expect(200);++ expect(typeof res.body.count).toBe("number");+ expect(Array.isArray(res.body.results)).toBe(true);+ });+});diff --git a/apps/server/src/routes/api/stats.spec.ts b/apps/server/src/routes/api/stats.spec.tsnew file mode 100644index 0000000000..a9f7526641--- /dev/null+++ b/apps/server/src/routes/api/stats.spec.ts@@ -0,0 +1,34 @@+import { beforeAll, describe, expect, it } from "vitest";++import { type ApiTestContext,bootLoggedInApp } from "../../../spec/support/internal_api.js";++let ctx: ApiTestContext;++describe("Stats API", () => {+ beforeAll(async () => {+ ctx = await bootLoggedInApp();+ });++ it("returns the blob size of a note", async () => {+ const res = await ctx.agent.get("/api/stats/note-size/root").expect(200);+ expect(typeof res.body.noteSize).toBe("number");+ expect(res.body.noteSize).toBeGreaterThanOrEqual(0);+ });++ it("returns the subtree size and note count", async () => {+ const res = await ctx.agent.get("/api/stats/subtree-size/root").expect(200);+ expect(typeof res.body.subTreeSize).toBe("number");+ expect(res.body.subTreeNoteCount).toBeGreaterThan(1);+ });++ // note-size runs a pure SQL aggregate (no note lookup), so a missing note is+ // 0 bytes rather than an error; subtree-size resolves the note first and 404s.+ it("reports zero size for a missing note", async () => {+ const res = await ctx.agent.get("/api/stats/note-size/missingNote123").expect(200);+ expect(res.body.noteSize).toBe(0);+ });++ it("404s for the subtree size of a missing note", async () => {+ await ctx.agent.get("/api/stats/subtree-size/missingNote123").expect(404);+ });+});diff --git a/apps/server/src/routes/api/tree.spec.ts b/apps/server/src/routes/api/tree.spec.tsnew file mode 100644index 0000000000..d871871716--- /dev/null+++ b/apps/server/src/routes/api/tree.spec.ts@@ -0,0 +1,57 @@+import { beforeAll, describe, expect, it } from "vitest";++import { type ApiTestContext,bootLoggedInApp } from "../../../spec/support/internal_api.js";++let ctx: ApiTestContext;++interface TreeResponse {+ notes: { noteId: string }[];+ branches: { branchId: string }[];+ attributes: unknown[];+}++describe("Tree API", () => {+ beforeAll(async () => {+ ctx = await bootLoggedInApp();+ });++ it("returns notes, branches and attributes rooted at root", async () => {+ const res = await ctx.agent.get("/api/tree").expect(200);+ const body = res.body as TreeResponse;++ expect(Array.isArray(body.notes)).toBe(true);+ expect(Array.isArray(body.branches)).toBe(true);+ expect(Array.isArray(body.attributes)).toBe(true);+ expect(body.notes.some((n) => n.noteId === "root")).toBe(true);+ // root always gets the synthetic `none_root` branch (parentNoteId "none").+ expect(body.branches.some((b) => b.branchId === "none_root")).toBe(true);+ });++ it("scopes the tree to a subtree via subTreeNoteId", async () => {+ const res = await ctx.agent+ .get("/api/tree")+ .query({ subTreeNoteId: "_hidden" })+ .expect(200);+ const body = res.body as TreeResponse;+ expect(body.notes.some((n) => n.noteId === "_hidden")).toBe(true);+ });++ it("404s for an unknown subtree note", async () => {+ await ctx.agent.get("/api/tree").query({ subTreeNoteId: "doesNotExist123" }).expect(404);+ });++ it("loads an explicit set of note ids", async () => {+ const res = await ctx.agent+ .post("/api/tree/load")+ .set("x-csrf-token", ctx.csrfToken)+ .send({ noteIds: [ "root" ] })+ .expect(200);+ const body = res.body as TreeResponse;++ expect(body.notes.some((n) => n.noteId === "root")).toBe(true);+ });++ it("rejects a mutating request without a CSRF token", async () => {+ await ctx.agent.post("/api/tree/load").send({ noteIds: [ "root" ] }).expect(403);+ });+});diff --git a/apps/server/tsconfig.spec.json b/apps/server/tsconfig.spec.jsonindex 2d13ec111c..d745f58aef 100644--- a/apps/server/tsconfig.spec.json+++ b/apps/server/tsconfig.spec.json@@ -26,6 +26,7 @@"src/**/*.d.ts","src/**/*.ts","src/**/*.json",+ "spec/support/**/*.ts","package.json"]}