Skip to content

Build your personal knowledge base with Trilium Notes

test(ckeditor5): centralize global stubs and the TestBox fixture in the test-kit

Elian Doran4d9f1ed169c3
diff --git a/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts b/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts
index 320137f9e6..3e8be819ae 100644
--- a/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts
+++ b/packages/ckeditor5/src/plugins/copy_anchor_link.spec.ts
@@ -1,7 +1,8 @@
import { _setModelData as setModelData, Bold, Bookmark, ClassicEditor, Essentials, Paragraph } from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock, mockClipboard } from "../../test/globals-test-kit.js";
import CopyAnchorLinkButton from "./copy_anchor_link.js";
describe("CopyAnchorLinkButton", () => {
@@ -9,34 +10,21 @@ describe("CopyAnchorLinkButton", () => {
let getActiveContextNote: ReturnType<typeof vi.fn>;
let getReferenceLinkTitleSync: ReturnType<typeof vi.fn>;
let clipboardWrite: ReturnType<typeof vi.fn>;
- let originalClipboard: typeof navigator.clipboard;
beforeEach(async () => {
getActiveContextNote = vi.fn(() => ({ noteId: "noteAbc" }));
getReferenceLinkTitleSync = vi.fn(() => "Some title");
- globalThis.glob = {
+ installGlobMock({
getActiveContextNote,
getReferenceLinkTitleSync
- } as unknown as typeof glob;
+ });
clipboardWrite = vi.fn(() => Promise.resolve());
- originalClipboard = navigator.clipboard;
- Object.defineProperty(navigator, "clipboard", {
- configurable: true,
- value: { write: clipboardWrite }
- });
+ mockClipboard({ write: clipboardWrite });
editor = await createTestEditor([Essentials, Paragraph, Bold, Bookmark, CopyAnchorLinkButton]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- Object.defineProperty(navigator, "clipboard", {
- configurable: true,
- value: originalClipboard
- });
- });
-
function getButton() {
return editor.ui.componentFactory.create("copyAnchorLink") as { fire(name: string): void };
}
diff --git a/packages/ckeditor5/src/plugins/cuttonote.spec.ts b/packages/ckeditor5/src/plugins/cuttonote.spec.ts
index 59122da412..39e600626e 100644
--- a/packages/ckeditor5/src/plugins/cuttonote.spec.ts
+++ b/packages/ckeditor5/src/plugins/cuttonote.spec.ts
@@ -1,7 +1,8 @@
import { _setModelData as setModelData, ClassicEditor, Essentials, Paragraph } from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import CutToNotePlugin from "./cuttonote.js";
describe("CutToNotePlugin", () => {
@@ -10,17 +11,13 @@ describe("CutToNotePlugin", () => {
beforeEach(async () => {
triggerCommand = vi.fn();
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({ triggerCommand })
- } as unknown as typeof glob;
+ });
editor = await createTestEditor([Essentials, Paragraph, CutToNotePlugin]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- });
-
it("loads the plugin and registers the toolbar button", () => {
expect(editor.plugins.get(CutToNotePlugin)).toBeInstanceOf(CutToNotePlugin);
expect(editor.ui.componentFactory.has("cutToNote")).toBe(true);
diff --git a/packages/ckeditor5/src/plugins/include_note_box_size_dropdown.spec.ts b/packages/ckeditor5/src/plugins/include_note_box_size_dropdown.spec.ts
index a45b97f4b3..62eefa40df 100644
--- a/packages/ckeditor5/src/plugins/include_note_box_size_dropdown.spec.ts
+++ b/packages/ckeditor5/src/plugins/include_note_box_size_dropdown.spec.ts
@@ -1,7 +1,8 @@
import { ClassicEditor, Essentials, Paragraph, Widget, _setModelData as setModelData } from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import IncludeNoteBoxSizeDropdown from "./include_note_box_size_dropdown.js";
import IncludeNote, { BOX_SIZE_COMMAND_NAME, BOX_SIZES } from "./includenote.js";
@@ -10,21 +11,13 @@ describe("IncludeNoteBoxSizeDropdown", () => {
beforeEach(async () => {
const loadIncludedNote = vi.fn();
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({ loadIncludedNote })
- } as unknown as typeof glob;
-
- // includenote.ts calls jQuery globally; provide a passthrough stub
- (globalThis as unknown as { $: (x: unknown) => unknown }).$ = (x) => x;
+ });
editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote, IncludeNoteBoxSizeDropdown]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- delete (globalThis as { $?: unknown }).$;
- });
-
it("loads the plugin and registers the dropdown component", () => {
expect(editor.plugins.get(IncludeNoteBoxSizeDropdown)).toBeInstanceOf(IncludeNoteBoxSizeDropdown);
expect(editor.ui.componentFactory.has("includeNoteBoxSizeDropdown")).toBe(true);
diff --git a/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts b/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
index 6182a56ecf..2d87c7ec7e 100644
--- a/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/include_note_toolbar.spec.ts
@@ -1,7 +1,8 @@
import { ClassicEditor, Essentials, Paragraph, Plugin, toWidget, Widget, WidgetToolbarRepository, _setModelData as setModelData } from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import IncludeNote from "./includenote.js";
import IncludeNoteBoxSizeDropdown from "./include_note_box_size_dropdown.js";
import IncludeNoteToolbar from "./include_note_toolbar.js";
@@ -74,21 +75,13 @@ describe("IncludeNoteToolbar", () => {
beforeEach(async () => {
const loadIncludedNote = vi.fn();
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({ loadIncludedNote })
- } as unknown as typeof glob;
-
- // includenote.ts calls jQuery globally; provide a passthrough stub.
- (globalThis as unknown as { $: (x: unknown) => unknown }).$ = (x) => x;
+ });
editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote, IncludeNoteBoxSizeDropdown, IncludeNoteToolbar]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- delete (globalThis as { $?: unknown }).$;
- });
-
it("loads the plugin", () => {
expect(editor.plugins.get(IncludeNoteToolbar)).toBeInstanceOf(IncludeNoteToolbar);
});
@@ -155,20 +148,13 @@ describe("isIncludeNoteWidget — section widget without a class attribute (|| '
beforeEach(async () => {
const loadIncludedNote = vi.fn();
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({ loadIncludedNote })
- } as unknown as typeof glob;
-
- (globalThis as unknown as { $: (x: unknown) => unknown }).$ = (x) => x;
+ });
editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote, IncludeNoteBoxSizeDropdown, IncludeNoteToolbar, SectionNoClassWidget]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- delete (globalThis as { $?: unknown }).$;
- });
-
it("returns null for a section widget that has no class attribute (exercises the || '' fallback at line 43)", () => {
// The SectionNoClassWidget editing downcast creates a real CKEditor widget (toWidget)
// wrapping a <section> element with NO class attribute. When that widget is selected:
@@ -204,7 +190,7 @@ describe("isIncludeNoteWidget — real non-include-note widgets (branch coverage
beforeEach(async () => {
const loadIncludedNote = vi.fn();
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({
loadIncludedNote,
renderLinkEmbed: vi.fn(),
@@ -220,19 +206,11 @@ describe("isIncludeNoteWidget — real non-include-note widgets (branch coverage
}),
detectEmbedType: () => "opengraph"
})
- } as unknown as typeof glob;
-
- // Both includenote.ts and linkembed.ts call jQuery globally.
- (globalThis as unknown as { $: (x: unknown) => unknown }).$ = (x) => x;
+ });
editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote, IncludeNoteBoxSizeDropdown, IncludeNoteToolbar, LinkEmbed]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- delete (globalThis as { $?: unknown }).$;
- });
-
it("returns null when getSelectedElement returns a non-widget element (covers the !isWidget branch at line 35-36)", () => {
// To hit `return false` at line 36 in isIncludeNoteWidget we need a non-null
// selected element for which isWidget() returns false. A plain JS object
diff --git a/packages/ckeditor5/src/plugins/includenote.spec.ts b/packages/ckeditor5/src/plugins/includenote.spec.ts
index f8a524f627..e792d26311 100644
--- a/packages/ckeditor5/src/plugins/includenote.spec.ts
+++ b/packages/ckeditor5/src/plugins/includenote.spec.ts
@@ -7,9 +7,10 @@ import {
Widget,
type ModelElement
} from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import IncludeNote, { BOX_SIZE_COMMAND_NAME, BOX_SIZES, COMMAND_NAME } from "./includenote.js";
describe("IncludeNote", () => {
@@ -20,21 +21,13 @@ describe("IncludeNote", () => {
beforeEach(async () => {
triggerCommand = vi.fn();
loadIncludedNote = vi.fn();
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({ triggerCommand, loadIncludedNote })
- } as unknown as typeof glob;
-
- // includenote.ts calls jQuery globally; provide a passthrough stub.
- (globalThis as unknown as { $: (x: unknown) => unknown }).$ = (x) => x;
+ });
editor = await createTestEditor([Essentials, Paragraph, Widget, IncludeNote]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- delete (globalThis as { $?: unknown }).$;
- });
-
// -----------------------------------------------------------------------
// Plugin / schema registration
// -----------------------------------------------------------------------
diff --git a/packages/ckeditor5/src/plugins/insert_date_time.spec.ts b/packages/ckeditor5/src/plugins/insert_date_time.spec.ts
index 9f6e83bd82..7309a8e6ed 100644
--- a/packages/ckeditor5/src/plugins/insert_date_time.spec.ts
+++ b/packages/ckeditor5/src/plugins/insert_date_time.spec.ts
@@ -1,7 +1,8 @@
import { ClassicEditor, Essentials, Paragraph } from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import InsertDateTimePlugin, { COMMAND_NAME } from "./insert_date_time.js";
describe("InsertDateTimePlugin", () => {
@@ -10,17 +11,13 @@ describe("InsertDateTimePlugin", () => {
beforeEach(async () => {
triggerCommand = vi.fn();
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({ triggerCommand })
- } as unknown as typeof glob;
+ });
editor = await createTestEditor([Essentials, Paragraph, InsertDateTimePlugin]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- });
-
it("loads the plugin and registers the command and toolbar button", () => {
expect(editor.plugins.get(InsertDateTimePlugin)).toBeInstanceOf(InsertDateTimePlugin);
expect(editor.commands.get(COMMAND_NAME)).toBeDefined();
diff --git a/packages/ckeditor5/src/plugins/internallink.spec.ts b/packages/ckeditor5/src/plugins/internallink.spec.ts
index f4affcb0bb..ca4dc5217d 100644
--- a/packages/ckeditor5/src/plugins/internallink.spec.ts
+++ b/packages/ckeditor5/src/plugins/internallink.spec.ts
@@ -1,7 +1,8 @@
import { _setModelData as setModelData, ClassicEditor, CodeBlock, Essentials, Paragraph } from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import InternalLinkPlugin, { COMMAND_NAME } from "./internallink.js";
describe("InternalLinkPlugin", () => {
@@ -10,17 +11,13 @@ describe("InternalLinkPlugin", () => {
beforeEach(async () => {
triggerCommand = vi.fn();
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({ triggerCommand })
- } as unknown as typeof glob;
+ });
editor = await createTestEditor([Essentials, Paragraph, CodeBlock, InternalLinkPlugin]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- });
-
it("loads the plugin and registers the command and toolbar button", () => {
expect(editor.plugins.get(InternalLinkPlugin)).toBeInstanceOf(InternalLinkPlugin);
expect(editor.commands.get(COMMAND_NAME)).toBeDefined();
diff --git a/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts b/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
index c5ea8d1587..4ff3cd105a 100644
--- a/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
+++ b/packages/ckeditor5/src/plugins/link_embed_toolbar.spec.ts
@@ -1,7 +1,8 @@
import { ClassicEditor, Essentials, Paragraph, WidgetToolbarRepository, _setModelData as setModelData } from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import LinkEmbedToolbar from "./link_embed_toolbar.js";
import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_DISPLAY_MODES } from "./linkembed.js";
@@ -75,7 +76,7 @@ describe("LinkEmbedToolbar", () => {
let editor: ClassicEditor;
beforeEach(async () => {
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({
renderLinkEmbed: vi.fn(),
renderLinkMention: vi.fn(),
@@ -90,18 +91,11 @@ describe("LinkEmbedToolbar", () => {
}),
detectEmbedType: () => "opengraph"
})
- } as unknown as typeof glob;
-
- (globalThis as unknown as { $: (x: unknown) => unknown }).$ = (x) => x;
+ });
editor = await createTestEditor([Essentials, Paragraph, LinkEmbed, LinkEmbedToolbar]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- delete (globalThis as { $?: unknown }).$;
- });
-
// -----------------------------------------------------------------------
// Plugin registration
// -----------------------------------------------------------------------
diff --git a/packages/ckeditor5/src/plugins/linkembed.spec.ts b/packages/ckeditor5/src/plugins/linkembed.spec.ts
index fee25cc47c..dd929b0a3a 100644
--- a/packages/ckeditor5/src/plugins/linkembed.spec.ts
+++ b/packages/ckeditor5/src/plugins/linkembed.spec.ts
@@ -6,11 +6,13 @@ import {
Essentials,
Link,
Paragraph,
- Undo
+ Undo,
+ type ViewElement
} from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import LinkEmbed, { CHANGE_LINK_DISPLAY_COMMAND, LINK_EMBED_COMMAND } from "./linkembed.js";
const META = {
@@ -39,7 +41,7 @@ describe("LinkEmbed", () => {
// YouTube-like URLs => "youtube" (embeddable); everything else => "opengraph".
detectEmbedType = vi.fn((url: string) => (url.includes("youtube") ? "youtube" : "opengraph"));
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({
triggerCommand,
renderLinkEmbed,
@@ -47,15 +49,11 @@ describe("LinkEmbed", () => {
fetchLinkMetadata,
detectEmbedType
})
- } as unknown as typeof glob;
+ });
editor = await createTestEditor([Essentials, Paragraph, BlockQuote, Link, Undo, LinkEmbed]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- });
-
// -----------------------------------------------------------------------
// Plugin / UI registration
// -----------------------------------------------------------------------
@@ -248,6 +246,41 @@ describe("LinkEmbed", () => {
expect(editable).toBe(true);
});
+ it("maps a view position inside the rendered linkMention to a model position OUTSIDE the object", () => {
+ // linkMention is an empty inline object whose editing view holds a UIElement child. Without
+ // the viewToModelPositionOutsideModelElement mapper registered in LinkEmbedEditing, a view
+ // position inside the rendered widget resolves to a degenerate model position *inside* the
+ // atomic object; the mapper must instead resolve it just after the mention.
+ setModelData(
+ editor.model,
+ '<paragraph>foo<linkMention url="https://e.com/" title="T"></linkMention>bar</paragraph>'
+ );
+
+ const root = editor.editing.view.document.getRoot();
+ let mentionView: ViewElement | undefined;
+ if (root) {
+ for (const { item } of editor.editing.view.createRangeIn(root)) {
+ if (item.is("element") && item.hasClass("link-mention")) {
+ mentionView = item;
+ break;
+ }
+ }
+ }
+ expect(mentionView).toBeDefined();
+ if (!mentionView) {
+ return;
+ }
+
+ const viewPosition = editor.editing.view.createPositionAt(mentionView, "end");
+ const modelPosition = editor.editing.mapper.toModelPosition(viewPosition);
+
+ // Must land just after the mention (paragraph offset 4 = "foo"(3) + linkMention(1)),
+ // not inside the atomic linkMention element.
+ expect(modelPosition.parent.is("element", "linkMention")).toBe(false);
+ expect(modelPosition.parent.is("element", "paragraph")).toBe(true);
+ expect(modelPosition.offset).toBe(4);
+ });
+
// -----------------------------------------------------------------------
// ChangeLinkDisplayCommand
// -----------------------------------------------------------------------
diff --git a/packages/ckeditor5/src/plugins/markdownimport.spec.ts b/packages/ckeditor5/src/plugins/markdownimport.spec.ts
index 297fe32ed5..1c5ba0fd2a 100644
--- a/packages/ckeditor5/src/plugins/markdownimport.spec.ts
+++ b/packages/ckeditor5/src/plugins/markdownimport.spec.ts
@@ -1,7 +1,8 @@
import { ClassicEditor, Essentials, Paragraph } from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import MarkdownImportPlugin, { COMMAND_NAME } from "./markdownimport.js";
describe("MarkdownImportPlugin", () => {
@@ -10,17 +11,13 @@ describe("MarkdownImportPlugin", () => {
beforeEach(async () => {
triggerCommand = vi.fn();
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({ triggerCommand })
- } as unknown as typeof glob;
+ });
editor = await createTestEditor([Essentials, Paragraph, MarkdownImportPlugin]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- });
-
it("loads the plugin and registers the command and toolbar button", () => {
expect(editor.plugins.get(MarkdownImportPlugin)).toBeInstanceOf(MarkdownImportPlugin);
expect(editor.commands.get(COMMAND_NAME)).toBeDefined();
diff --git a/packages/ckeditor5/src/plugins/mention_customization.spec.ts b/packages/ckeditor5/src/plugins/mention_customization.spec.ts
index 741470c4ab..fdae624d30 100644
--- a/packages/ckeditor5/src/plugins/mention_customization.spec.ts
+++ b/packages/ckeditor5/src/plugins/mention_customization.spec.ts
@@ -6,9 +6,10 @@ import {
Mention,
Paragraph
} from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import MentionCustomization from "./mention_customization.js";
import ReferenceLink from "./referencelink.js";
@@ -18,17 +19,14 @@ describe("MentionCustomization", () => {
beforeEach(async () => {
createNoteForReferenceLink = vi.fn(async () => "createdNotePath");
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({
createNoteForReferenceLink,
loadReferenceLinkTitle: vi.fn(async () => {})
}),
getReferenceLinkTitle: vi.fn(async () => "Some title"),
getReferenceLinkTitleSync: () => "Some title"
- } as unknown as typeof glob;
-
- // referencelink.ts editing downcast converter calls jQuery globally.
- (globalThis as unknown as { $: (x: unknown) => unknown }).$ = (x) => x;
+ });
editor = await createTestEditor([
Essentials,
@@ -39,11 +37,6 @@ describe("MentionCustomization", () => {
]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- delete (globalThis as { $?: unknown }).$;
- });
-
it("loads the plugin, requires Mention and overrides the mention command", () => {
expect(editor.plugins.get(MentionCustomization)).toBeInstanceOf(MentionCustomization);
expect(MentionCustomization.pluginName).toBe("MentionCustomization");
diff --git a/packages/ckeditor5/src/plugins/move_block_updown.spec.ts b/packages/ckeditor5/src/plugins/move_block_updown.spec.ts
index 788ad651d1..478cedb1d0 100644
--- a/packages/ckeditor5/src/plugins/move_block_updown.spec.ts
+++ b/packages/ckeditor5/src/plugins/move_block_updown.spec.ts
@@ -4,13 +4,12 @@ import {
Essentials,
Paragraph,
Plugin,
- toWidget,
- Widget,
} from "ckeditor5";
import type { ModelElement, ModelText } from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { TestBoxPlugin } from "../../test/fixture-plugins.js";
import MoveBlockUpDownPlugin from "./move_block_updown.js";
/** Returns the text data of the Nth block in the editor root (0-indexed). */
@@ -24,46 +23,6 @@ function getBlockText(editor: ClassicEditor, index: number): string {
return (textNode as ModelText).data;
}
-/**
- * Minimal block widget plugin for testing the object-element path.
- * Registers a `testBox` element with isObject: true so that selecting it
- * exercises the `getSelectedElement()` branch and the else-branch for
- * selection restoration.
- */
-class TestBoxPlugin extends Plugin {
- static get requires() {
- return [Widget];
- }
-
- init() {
- const { model, conversion } = this.editor;
-
- model.schema.register("testBox", {
- isObject: true,
- allowWhere: "$block"
- });
-
- conversion.for("upcast").elementToElement({
- model: "testBox",
- view: { name: "div", classes: "test-box" }
- });
-
- conversion.for("dataDowncast").elementToElement({
- model: "testBox",
- view: (_el, { writer }) =>
- writer.createContainerElement("div", { class: "test-box" })
- });
-
- conversion.for("editingDowncast").elementToElement({
- model: "testBox",
- view: (_el, { writer }) => {
- const container = writer.createContainerElement("div", { class: "test-box" });
- return toWidget(container, writer, { label: "test box widget" });
- }
- });
- }
-}
-
describe("MoveBlockUpDownPlugin", () => {
let editor: ClassicEditor;
diff --git a/packages/ckeditor5/src/plugins/referencelink.spec.ts b/packages/ckeditor5/src/plugins/referencelink.spec.ts
index 27a211feff..da6edbf7ad 100644
--- a/packages/ckeditor5/src/plugins/referencelink.spec.ts
+++ b/packages/ckeditor5/src/plugins/referencelink.spec.ts
@@ -1,7 +1,8 @@
import { _getViewData as getViewData, _setModelData as setModelData, ClassicEditor, Essentials, LinkEditing, Paragraph } from "ckeditor5";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import ReferenceLink from "./referencelink.js";
describe("ReferenceLink", () => {
@@ -14,23 +15,15 @@ describe("ReferenceLink", () => {
getReferenceLinkTitle = vi.fn(async () => "Some title");
getReferenceLinkTitleSync = vi.fn(() => "Some title");
loadReferenceLinkTitle = vi.fn(async () => undefined);
- globalThis.glob = {
+ installGlobMock({
getComponentByEl: () => ({ loadReferenceLinkTitle }),
getReferenceLinkTitle,
getReferenceLinkTitleSync
- } as unknown as typeof glob;
-
- // The editingDowncast and upcast converters call jQuery via a global `$`.
- (globalThis as unknown as { $: (x: unknown) => unknown }).$ = (x) => x;
+ });
editor = await createTestEditor([Essentials, Paragraph, LinkEditing, ReferenceLink]);
});
- afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
- delete (globalThis as { $?: unknown }).$;
- });
-
it("loads the plugin, registers the schema and the command", () => {
expect(editor.plugins.get(ReferenceLink)).toBeInstanceOf(ReferenceLink);
expect(editor.commands.get("referenceLink")).toBeDefined();
diff --git a/packages/ckeditor5/src/plugins/uploadimage.spec.ts b/packages/ckeditor5/src/plugins/uploadimage.spec.ts
index 485c0d69f6..3ef3955fd6 100644
--- a/packages/ckeditor5/src/plugins/uploadimage.spec.ts
+++ b/packages/ckeditor5/src/plugins/uploadimage.spec.ts
@@ -2,6 +2,7 @@ import { ClassicEditor, Essentials, FileRepository, Paragraph, type FileLoader,
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { installGlobMock } from "../../test/globals-test-kit.js";
import UploadimagePlugin from "./uploadimage.js";
/**
@@ -80,10 +81,10 @@ describe("UploadimagePlugin", () => {
beforeEach(async () => {
getHeaders = vi.fn(async () => ({ Authorization: "Bearer token", "x-csrf": "abc" }));
- globalThis.glob = {
+ installGlobMock({
getHeaders,
getActiveContextNote: () => ({ noteId: "noteAbc" })
- } as unknown as typeof glob;
+ });
originalXHR = window.XMLHttpRequest;
window.XMLHttpRequest = FakeXHR as unknown as typeof window.XMLHttpRequest;
@@ -93,7 +94,6 @@ describe("UploadimagePlugin", () => {
});
afterEach(() => {
- delete (globalThis as { glob?: unknown }).glob;
window.XMLHttpRequest = originalXHR;
});
diff --git a/packages/ckeditor5/src/plugins/widget_utils.spec.ts b/packages/ckeditor5/src/plugins/widget_utils.spec.ts
index 519cf1db89..d141541f12 100644
--- a/packages/ckeditor5/src/plugins/widget_utils.spec.ts
+++ b/packages/ckeditor5/src/plugins/widget_utils.spec.ts
@@ -2,58 +2,14 @@ import {
ClassicEditor,
Essentials,
Paragraph,
- Plugin,
- toWidget,
- Widget,
_setModelData as setModelData,
} from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
+import { TestBoxPlugin } from "../../test/fixture-plugins.js";
import { preventCKEditorHandling } from "./widget_utils.js";
-/**
- * Minimal block widget plugin for test purposes.
- *
- * It registers a `testBox` element that renders as a <div data-cke-widget-wrapper> block
- * so we can exercise the full selectParentWidget path.
- */
-class TestBoxPlugin extends Plugin {
- static get requires() {
- return [Widget];
- }
-
- init() {
- const { model, conversion } = this.editor;
-
- model.schema.register("testBox", {
- isObject: true,
- allowWhere: "$block",
- });
-
- conversion.for("upcast").elementToElement({
- model: "testBox",
- view: { name: "div", classes: "test-box" },
- });
-
- conversion.for("dataDowncast").elementToElement({
- model: "testBox",
- view: (_el, { writer }) =>
- writer.createContainerElement("div", { class: "test-box" }),
- });
-
- conversion.for("editingDowncast").elementToElement({
- model: "testBox",
- view: (_el, { writer }) => {
- const container = writer.createContainerElement("div", {
- class: "test-box",
- });
- return toWidget(container, writer, { label: "test box widget" });
- },
- });
- }
-}
-
describe("preventCKEditorHandling", () => {
let editor: ClassicEditor;
diff --git a/packages/ckeditor5/test/fixture-plugins.ts b/packages/ckeditor5/test/fixture-plugins.ts
new file mode 100644
index 0000000000..c8af6a0d23
--- /dev/null
+++ b/packages/ckeditor5/test/fixture-plugins.ts
@@ -0,0 +1,40 @@
+import { Plugin, toWidget, Widget } from "ckeditor5";
+
+/**
+ * Minimal block widget plugin for tests: registers a `testBox` object element (isObject, allowed
+ * wherever a block is) that downcasts to `<div class="test-box">` and is wrapped as a widget in
+ * the editing view. Used to exercise object-element / widget-selection paths. Extracted from the
+ * specs that each defined an identical copy.
+ */
+export class TestBoxPlugin extends Plugin {
+ static get requires() {
+ return [Widget];
+ }
+
+ init() {
+ const { model, conversion } = this.editor;
+
+ model.schema.register("testBox", {
+ isObject: true,
+ allowWhere: "$block"
+ });
+
+ conversion.for("upcast").elementToElement({
+ model: "testBox",
+ view: { name: "div", classes: "test-box" }
+ });
+
+ conversion.for("dataDowncast").elementToElement({
+ model: "testBox",
+ view: (_el, { writer }) => writer.createContainerElement("div", { class: "test-box" })
+ });
+
+ conversion.for("editingDowncast").elementToElement({
+ model: "testBox",
+ view: (_el, { writer }) => {
+ const container = writer.createContainerElement("div", { class: "test-box" });
+ return toWidget(container, writer, { label: "test box widget" });
+ }
+ });
+ }
+}
diff --git a/packages/ckeditor5/test/globals-test-kit.ts b/packages/ckeditor5/test/globals-test-kit.ts
new file mode 100644
index 0000000000..96634a5b10
--- /dev/null
+++ b/packages/ckeditor5/test/globals-test-kit.ts
@@ -0,0 +1,51 @@
+/**
+ * Helpers for the Trilium global stubs that several specs install on `globalThis` (the `glob`
+ * bridge and `navigator.clipboard`). Each installer registers its own teardown, run after every
+ * test by the global `afterEach` in `setup.ts`, so specs no longer need to delete/restore these
+ * themselves.
+ *
+ * Lives outside `src/`, so it is excluded from both the production build and the 100% coverage
+ * gate (see editor-kit.ts).
+ */
+
+const cleanups: Array<() => void | Promise<void>> = [];
+
+/** Queue a teardown to run after the current test (LIFO), via runTestCleanups() in setup.ts. */
+export function registerTestCleanup(cleanup: () => void | Promise<void>): void {
+ cleanups.push(cleanup);
+}
+
+/** Run and clear all queued per-test cleanups, most-recently-registered first. */
+export async function runTestCleanups(): Promise<void> {
+ const pending = cleanups.splice(0).reverse();
+ for (const cleanup of pending) {
+ await cleanup();
+ }
+}
+
+/**
+ * Install a mock Trilium `glob` on `globalThis` for the current test. Pass only the members the
+ * spec needs (each typically a `vi.fn()`); the cast to the global `glob` type lives here so specs
+ * don't repeat it. Returns the same object for convenient assertion access. Removed automatically
+ * after the test.
+ */
+export function installGlobMock<T extends object>(glob: T): T {
+ (globalThis as unknown as { glob: T }).glob = glob;
+ registerTestCleanup(() => {
+ delete (globalThis as { glob?: unknown }).glob;
+ });
+ return glob;
+}
+
+/**
+ * Replace `navigator.clipboard` with the given mock for the current test, restoring the original
+ * afterwards. Returns the mock for assertion access.
+ */
+export function mockClipboard<T extends object>(clipboard: T): T {
+ const original = navigator.clipboard;
+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: clipboard });
+ registerTestCleanup(() => {
+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: original });
+ });
+ return clipboard;
+}
diff --git a/packages/ckeditor5/test/setup.ts b/packages/ckeditor5/test/setup.ts
index 6b8d08e9d9..35d82e4002 100644
--- a/packages/ckeditor5/test/setup.ts
+++ b/packages/ckeditor5/test/setup.ts
@@ -1,12 +1,20 @@
-import { afterEach } from "vitest";
+import { afterEach, beforeEach } from "vitest";
import { destroyTrackedEditors } from "./editor-kit.js";
+import { runTestCleanups } from "./globals-test-kit.js";
/**
- * Global test setup, registered via `setupFiles` in vitest.config.ts and run before every
- * spec. Owns the editor teardown that each spec used to repeat: any editor created through
- * `createTestEditor()` is destroyed and its host element removed after every test.
+ * Global test setup, registered via `setupFiles` in vitest.config.ts and run before/after every
+ * spec. Owns the boilerplate specs used to repeat:
+ * - a constant `$` (jQuery) passthrough that several plugins' converters call;
+ * - destroying every editor created through `createTestEditor()`;
+ * - running per-test cleanups queued by the globals kit (glob / clipboard stubs).
*/
+beforeEach(() => {
+ (globalThis as unknown as { $: (value: unknown) => unknown }).$ = (value) => value;
+});
+
afterEach(async () => {
+ await runTestCleanups();
await destroyTrackedEditors();
});