Skip to content

Build your personal knowledge base with Trilium Notes

test(server): get rid of non-null assertions

Elian Doran553780c77512
diff --git a/.claude/skills/writing-unit-tests/SKILL.md b/.claude/skills/writing-unit-tests/SKILL.md
index 9231982fca..3f359d7d06 100644
--- a/.claude/skills/writing-unit-tests/SKILL.md
+++ b/.claude/skills/writing-unit-tests/SKILL.md
@@ -57,6 +57,7 @@ coverage: {
## Universal gotchas
+- **No non-null assertions (`!`)** — never use the TypeScript postfix `!` operator, even in tests. Narrow instead: `becca.getNoteOrThrow(id)`/`getAttachmentOrThrow(id)` instead of `becca.getNote(id)!`; `value?.prop ?? fallback` then assert; or capture into a const after an `expect(x).toBeDefined()`/null check. (Project rule — see `CLAUDE.md` Code Style.)
- **`vi.mock` is hoisted** above imports. Put component/module imports *after* the `vi.mock(...)` calls; mock factories can't reference outer non-hoisted variables. Partial-mock with `async (importOriginal) => ({ ...(await importOriginal()), onlyThis: vi.fn() })`.
- **Don't assert on translated (i18n) strings** — assert structure/keys/behavior (classes, counts, ids), not human-readable English.
- **happy-dom is not a browser:** `getBoundingClientRect()` returns zeros, `ResizeObserver`/layout/visibility are stubs. Anything pixel/size/scroll-based needs `@vitest/browser`, not happy-dom.
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 8daf10a65f..23ce943d70 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -254,6 +254,7 @@ Tools are defined using `defineTools()` in `apps/server/src/services/llm/tools/`
- **Build order**: `pnpm typecheck` builds all projects in dependency order
- **Build system**: Uses Vite for fast development, ESBuild for production optimization
- **Patches**: Custom patches in `patches/` directory for CKEditor and other dependencies
+- **No non-null assertions**: Never use the TypeScript non-null assertion operator (postfix `!`), including in tests. Narrow instead — optional chaining (`?.`), a `?? fallback`, an explicit null check, or an `*OrThrow` accessor (e.g. `becca.getNoteOrThrow(id)` rather than `becca.getNote(id)!`).
## Key Files for Context
diff --git a/CLAUDE.md b/CLAUDE.md
index 51f1387e71..fcf275ad38 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -265,6 +265,7 @@ Use `note.getOwnedAttribute()` for direct, `note.getAttribute()` for inherited.
- Max line length: 100 characters
- Unix line endings
- Import sorting via `eslint-plugin-simple-import-sort`
+- **Never use the TypeScript non-null assertion operator (postfix `!`)** — including in tests. Narrow instead: optional chaining (`?.`), a `?? fallback`, an explicit null check before use, or an `*OrThrow` accessor (e.g. `becca.getNoteOrThrow(id)` rather than `becca.getNote(id)!`).
## Testing
diff --git a/apps/server/src/routes/api/database.spec.ts b/apps/server/src/routes/api/database.spec.ts
index df6de2cd82..d1a515782a 100644
--- a/apps/server/src/routes/api/database.spec.ts
+++ b/apps/server/src/routes/api/database.spec.ts
@@ -84,10 +84,10 @@ describe("Database API", () => {
try {
const { res, calls } = fakeRes();
databaseRoute.downloadBackup({ query: { filePath } } as unknown as Request, res);
- expect(calls.download).toBeDefined();
- expect(calls.download![0]).toBe(path.resolve(filePath));
+ const downloadArgs = calls.download ?? [];
+ expect(downloadArgs[0]).toBe(path.resolve(filePath));
// A timestamped download filename is generated from the file mtime.
- expect(String(calls.download![1])).toMatch(/spec-backup_.*\.db/);
+ expect(String(downloadArgs[1])).toMatch(/spec-backup_.*\.db/);
} finally {
fs.rmSync(filePath, { force: true });
}
diff --git a/apps/server/src/routes/api/etapi_tokens.spec.ts b/apps/server/src/routes/api/etapi_tokens.spec.ts
index 98bd0d1d8e..803e032b3c 100644
--- a/apps/server/src/routes/api/etapi_tokens.spec.ts
+++ b/apps/server/src/routes/api/etapi_tokens.spec.ts
@@ -13,9 +13,8 @@ describe("ETAPI tokens API", () => {
const created = cls.init(() => etapiTokensRoute.createToken(req({ tokenName: "spec-token" })));
expect(created.authToken).toBeTruthy();
- const etapiTokenId = cls.init(() =>
- etapiTokensRoute.getTokens().find(t => t.name === "spec-token")!.etapiTokenId
- )!;
+ const token = cls.init(() => etapiTokensRoute.getTokens().find(t => t.name === "spec-token"));
+ const etapiTokenId = token?.etapiTokenId ?? "";
expect(etapiTokenId).toBeTruthy();
cls.init(() => etapiTokensRoute.patchToken(req({ name: "renamed" }, { etapiTokenId })));
diff --git a/apps/server/src/routes/api/files.spec.ts b/apps/server/src/routes/api/files.spec.ts
index 2839fc9c4d..56cab1ca8a 100644
--- a/apps/server/src/routes/api/files.spec.ts
+++ b/apps/server/src/routes/api/files.spec.ts
@@ -40,7 +40,7 @@ describe("Files API", () => {
const file = { buffer: Buffer.from("replaced"), mimetype: "TEXT/Plain", originalname: "new.txt" };
const result = cls.init(() => filesRoute.updateFile(fileReq({ noteId }, file, { replace: "1" })));
expect(result).toEqual({ uploaded: true });
- expect(becca.getNote(noteId)!.mime).toBe("text/plain");
+ expect(becca.getNoteOrThrow(noteId).mime).toBe("text/plain");
});
it("saves a revision when not replacing", () => {
@@ -64,7 +64,7 @@ describe("Files API", () => {
describe("content providers", () => {
it("streams full and ranged note content", async () => {
- const current = becca.getNote(noteId)!.getContent() as string;
+ const current = becca.getNoteOrThrow(noteId).getContent() as string;
const provider = await filesRoute.fileContentProvider(fileReq({ noteId }));
expect(provider.totalSize).toBe(Buffer.byteLength(current));
expect(await streamToString(provider.getStream(undefined as never))).toBe(current);
@@ -86,7 +86,7 @@ describe("Files API", () => {
fs.writeFileSync(tmpFilePath, "edited-on-disk");
cls.init(() => filesRoute.uploadModifiedFileToNote(fileReq({ noteId }, undefined, {}, { filePath: tmpFilePath })));
- expect(becca.getNote(noteId)!.getContent()).toBe("edited-on-disk");
+ expect(becca.getNoteOrThrow(noteId).getContent()).toBe("edited-on-disk");
});
it("saves an attachment to a temp file then uploads it back", () => {
@@ -95,7 +95,7 @@ describe("Files API", () => {
fs.writeFileSync(tmpFilePath, "edited-att");
const uploadReq = fileReq({ attachmentId } as Record<string, string>, undefined, {}, { filePath: tmpFilePath }) as unknown as Request<{ attachmentId: string }>;
cls.init(() => filesRoute.uploadModifiedFileToAttachment(uploadReq));
- expect(becca.getAttachment(attachmentId)!.getContent()).toBe("edited-att");
+ expect(becca.getAttachmentOrThrow(attachmentId).getContent()).toBe("edited-att");
});
it("rejects uploading from an unknown temp path", () => {
diff --git a/apps/server/src/routes/api/ocr.spec.ts b/apps/server/src/routes/api/ocr.spec.ts
index 71d5717531..176e482758 100644
--- a/apps/server/src/routes/api/ocr.spec.ts
+++ b/apps/server/src/routes/api/ocr.spec.ts
@@ -98,7 +98,7 @@ describe("OCR API", () => {
});
it("returns stored OCR text from the blob", async () => {
- const blobId = becca.getNote(noteId)!.blobId;
+ const blobId = becca.getNoteOrThrow(noteId).blobId;
cls.init(() => getSql().execute("UPDATE blobs SET textRepresentation = ? WHERE blobId = ?", ["scanned text", blobId]));
const result = await ocrRoutes.getNoteOCRText({ params: { noteId } } as unknown as Request<{ noteId: string }>);
expect(result).toEqual({ success: true, text: "scanned text", hasOcr: true });
diff --git a/apps/server/src/routes/session_parser.spec.ts b/apps/server/src/routes/session_parser.spec.ts
index ac12a9415f..f3fbcd0840 100644
--- a/apps/server/src/routes/session_parser.spec.ts
+++ b/apps/server/src/routes/session_parser.spec.ts
@@ -51,10 +51,11 @@ describe("SQLiteSessionStore", () => {
it("touch renews a non-persistent session but leaves a persistent one untouched", async () => {
await set("sess-3", baseSession());
- const before = store.getSessionExpiry("sess-3")!.getTime();
+ const before = store.getSessionExpiry("sess-3")?.getTime() ?? 0;
+ expect(before).toBeGreaterThan(0);
// No cookie.expires → touch pushes the expiry forward.
await touch("sess-3", baseSession());
- expect(store.getSessionExpiry("sess-3")!.getTime()).toBeGreaterThanOrEqual(before);
+ expect(store.getSessionExpiry("sess-3")?.getTime() ?? 0).toBeGreaterThanOrEqual(before);
// cookie.expires present → touch is a no-op (early return).
await touch("sess-3", baseSession(new Date(Date.now() + 60_000)));