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
chore(skills): add CKEditor 5 testing skill
Elian Doran99db3cbf156e
diff --git a/.claude/skills/ckeditor5-plugin-development/SKILL.md b/.claude/skills/ckeditor5-plugin-development/SKILL.mdindex a4e899ed34..a6f7ad4a03 100644--- a/.claude/skills/ckeditor5-plugin-development/SKILL.md+++ b/.claude/skills/ckeditor5-plugin-development/SKILL.md@@ -187,6 +187,9 @@ Load the focused reference for the task at hand:| `references/review-checklist.md` | A structured checklist for reviewing an existing plugin (architecture, schema, conversion, commands, UI, a11y, conventions). || `references/recipes.md` | Task-oriented how-tos: insert content, find/iterate nodes, custom observers, place caret, extend other plugins' UI, etc. |+For **testing** a plugin (Vitest setup, test editors, model/view assertions, command/UI test+patterns), use the separate **`ckeditor5-testing`** skill.+## Quick review checklist (summary)When reviewing a plugin, confirm: editing/UI split with a glue plugin; `static get requires()`diff --git a/.claude/skills/ckeditor5-testing/SKILL.md b/.claude/skills/ckeditor5-testing/SKILL.mdnew file mode 100644index 0000000000..aaa837925f--- /dev/null+++ b/.claude/skills/ckeditor5-testing/SKILL.md@@ -0,0 +1,171 @@+---+name: ckeditor5-testing+description: >-+ Write and run tests for CKEditor 5 plugins/features. Use when adding or+ reviewing unit tests for a ckeditor5-* package, debugging a failing test,+ migrating tests to Vitest, or setting up the test runner. Covers the current+ Vitest + Playwright browser setup, the test-editor utilities+ (ClassicTestEditor / VirtualTestEditor / ModelTestEditor), the model/view test+ helpers (_setModelData/_getModelData/_getViewData and their {}/[] selection+ syntax), vi spies/mocks, idiomatic patterns for schema/conversion/command/UI+ tests, the --files runner options, and migrating off the old Karma/Mocha/Chai+ setup. Complements the ckeditor5-plugin-development skill.+---++# CKEditor 5 testing++CKEditor 5 keeps a **complete unit-test suite with 100% code coverage per package**. Each+package owns its tests in `packages/ckeditor5-<name>/tests/`. Every code change should ship+with a test that proves it is needed.++> **Important — the published docs are out of date.** The official "Testing environment" guide+> describes **Karma + Mocha + Chai + Sinon**. The repository has **migrated to Vitest**+> (browser mode via Playwright). Write new/edited tests in the **Vitest** style described here;+> treat Chai/Sinon idioms (`expect().to.equal`, `sinon.spy`, `equalMarkup`) as legacy to be+> migrated, not copied. See `references/migration-from-karma.md`.++## When to use this skill++Adding/reviewing unit tests for a feature, debugging a failing test, migrating a legacy test+file to Vitest, or configuring the runner. For writing the feature itself, use the+`ckeditor5-plugin-development` skill.++## The current setup at a glance++- **Runner:** Vitest (`vitest@^4`), one **project per package**. Config comes from the root+ `createVitestConfig({ name: '<short-package-name>' })` factory; each package has a tiny+ `vitest.config.ts` that calls it.+- **Environment:** real browser via `@vitest/browser-playwright` (Chromium). Tests have real+ DOM APIs (`document.createElement`, etc.).+- **Globals:** `globals: true` is set, but migrated tests still **import explicitly** from+ `vitest` — do the same.+- **Test files:** `tests/**/*.{js,ts}`; excluded: `**/_utils`, `**/fixtures`, `**/manual`.+- **Setup:** `test_setup.js` sets `globalThis.CKEDITOR_GLOBAL_LICENSE_KEY = 'GPL'` — you do+ **not** pass a license key in tests.+- **Coverage:** `src/**` at **100%** thresholds (excludes `index.ts`, `augmentation.ts`,+ `*config.ts`). Provider `v8`.+- **TypeScript:** tests may be `.js` or `.ts`; import source with explicit `.js` extension+ (`../src/foo.js`).++## Running tests++Per-package (from the package dir) — the everyday loop:++```bash+vitest run # one-shot ("test" script)+vitest # watch / debug ("test:debug")+vitest run --browser.headless # headless ("test:headless")+pnpm run coverage # headless + coverage (100% gate)+vitest run paragraphcommand # filter by file name substring+```++From the repo root, the dev-tools wrapper runs the suite and accepts `--files` patterns+(see `references/running-and-config.md`):++```bash+pnpm run test # ckeditor5-dev-tests-run-automated (wraps Vitest)+pnpm run test -- --files=paragraph # one package (short name)+pnpm run test -- -c --files=core # with coverage+```++`--files` rules (shared with manual tests): `core` or `ckeditor5-core` (a package),+`editor-*` (glob), `!core` / `!(core|engine)` (exclude), `engine/view/` (a sub-dir),+`basic-styles/bold*` (file glob), comma-separated sums.++## Anatomy of a test++```js+/**+ * @license Copyright (c) 2003-2026, CKSource Holding sp. z o.o. All rights reserved.+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-licensing-options+ */++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { ModelTestEditor } from '@ckeditor/ckeditor5-core/tests/_utils/modeltesteditor.js';+import { _setModelData, _getModelData } from '@ckeditor/ckeditor5-engine';+import { ParagraphCommand } from '../src/paragraphcommand.js';++describe( 'ParagraphCommand', () => {+ let editor, model, command;++ beforeEach( () => {+ return ModelTestEditor.create().then( newEditor => {+ editor = newEditor;+ model = editor.model;+ command = new ParagraphCommand( editor );+ editor.commands.add( 'paragraph', command );+ model.schema.register( 'paragraph', { inheritAllFrom: '$block' } );+ model.schema.register( 'heading1', { inheritAllFrom: '$block' } );+ } );+ } );++ afterEach( () => {+ command.destroy(); // or editor.destroy() when you create a full editor+ } );++ it( 'is true when selection is in a paragraph', () => {+ _setModelData( model, '<paragraph>foo[]bar</paragraph>' );+ expect( command.value ).toBe( true );+ } );+} );+```++Conventions visible here and across the suite:+- Start with the **license header**. Keep one top-level `describe` named after the unit, with+ nested `describe`s for areas (`value`, `execute()`, …) and small focused `it`s.+- Create the editor in `beforeEach` (return the Promise — Vitest awaits it). **Always tear+ down** in `afterEach` (`editor.destroy()`, and remove any DOM element you appended).+- Use the lightest test editor that works: `ModelTestEditor` (model only) < `VirtualTestEditor`+ (model+engine, no DOM render) < `ClassicTestEditor` (full UI in a real element). Details in+ `references/test-utilities.md`.++## Model/view test data++`_setModelData()` / `_getModelData()` (and `_getViewData()`/`_setViewData()`) stringify and+parse the engine structures, with a special selection syntax:++- `[]` — collapsed selection, **or** brackets around a range, anchored in an **element**.+- `{}` — selection anchored inside a **text node** (e.g. `foo{}bar` / `f{oo}bar`).+- Attributes render as `<$text bold="true">word</$text>`; elements as `<paragraph>…</paragraph>`.++```js+_setModelData( model, '<paragraph>foo[]bar</paragraph>' );+expect( _getModelData( model ) ).toEqual( '<paragraph>foo[]bar</paragraph>' );+expect( _getViewData( editor.editing.view ) ).toEqual( '<p>foo{}bar</p>' );+```++These are dev/test utilities only — never ship them in production code.++## Assertions & spies (Vitest)++- Matchers: `expect(x).toBe()`, `.toEqual()`, `.toBeInstanceOf()`, `.toHaveBeenCalledOnce()`,+ `.toHaveBeenCalledWith()`, `.toThrow()`. There are **no** custom Chai matchers (`equalMarkup`,+ `.attribute`) — compare stringified model/view with `.toEqual()` instead.+- Spies/mocks via `vi`: `const spy = vi.spyOn( editor, 'execute' );` then+ `expect( spy ).toHaveBeenCalledWith( 'paragraph' )`. Also `vi.fn()`, `vi.useFakeTimers()`,+ `vi.stubGlobal()`. (Replaces Sinon — see the migration reference.)++```js+const spy = vi.spyOn( editor, 'execute' );+button.fire( 'execute' );+expect( spy ).toHaveBeenCalledOnce();+expect( spy ).toHaveBeenCalledWith( 'paragraph' );+```++## Reference map++| File | Use it for |+|------|-----------|+| `references/test-utilities.md` | The test editors (`ModelTestEditor`/`VirtualTestEditor`/`ClassicTestEditor`), other `_utils` (`articlepluginset`, `cleanup`, `generatelicensekey`), and the `_get/_set/_stringify/_parse` model & view helpers + selection syntax. |+| `references/patterns.md` | Idiomatic test recipes per concern: schema, conversion round-trips, commands (`value`/`isEnabled`/`execute`), UI (component factory, button binding, execute spy), keystrokes, events, async, and reaching 100% coverage. |+| `references/running-and-config.md` | Full runner reference: per-package vs. root wrapper, `--files` patterns, coverage/headless/watch, the `createVitestConfig` factory, browser mode, manual tests (md/js/html), memory-leak tests. |+| `references/migration-from-karma.md` | Mapping legacy Karma/Mocha/Chai/Sinon idioms to Vitest — for migrating existing test files (the repo is mid-migration). |++## Quick review checklist++When reviewing tests: license header present; explicit `vitest` imports; lightest suitable+test editor; editor/command created in `beforeEach` and **destroyed** in `afterEach` (plus DOM+cleanup); model/view asserted via `_getModelData`/`_getViewData` + `toEqual` with correct+`[]`/`{}` selection syntax; spies via `vi`; behavior covered for collapsed **and** ranged+selections and schema-disallowed contexts; new `src/` lines covered (100% gate); no Chai/Sinon+leftovers; manual tests (if any) under `tests/manual/`.diff --git a/.claude/skills/ckeditor5-testing/references/migration-from-karma.md b/.claude/skills/ckeditor5-testing/references/migration-from-karma.mdnew file mode 100644index 0000000000..d573b30acc--- /dev/null+++ b/.claude/skills/ckeditor5-testing/references/migration-from-karma.md@@ -0,0 +1,94 @@+# Migrating tests: Karma/Mocha/Chai/Sinon → Vitest++The repo is mid-migration (recent commits migrate packages one by one to Vitest). Many test+files still use the old stack. When you touch a legacy test, migrate it. This is the mapping.++## Imports & globals++- **Add explicit imports** at the top: `import { describe, it, expect, beforeEach, afterEach,+ vi } from 'vitest';` (the old globals from Mocha/Chai are gone; `globals: true` is set but the+ codebase imports explicitly).+- Keep the **license header** comment.+- Source imports use the **`.js` extension**: `import { Foo } from '../src/foo.js';`.+- Drop any `import { expect } from 'chai'` / Chai plugin setup.++## Test structure++- `describe`/`it`/`beforeEach`/`afterEach` keep the same names and semantics — usually no change+ beyond importing them.+- Async setup: returning a Promise still works; `async`/`await` is fine too.++## Assertions: Chai → Vitest `expect`++| Chai (old) | Vitest (new) |+|------------|--------------|+| `expect( x ).to.equal( y )` | `expect( x ).toBe( y )` |+| `expect( x ).to.deep.equal( y )` | `expect( x ).toEqual( y )` |+| `expect( x ).to.be.true` / `.false` | `expect( x ).toBe( true )` / `toBe( false )` |+| `expect( x ).to.be.null` / `.undefined` | `expect( x ).toBeNull()` / `toBeUndefined()` |+| `expect( x ).to.be.instanceOf( C )` | `expect( x ).toBeInstanceOf( C )` |+| `expect( arr ).to.have.length( n )` | `expect( arr ).toHaveLength( n )` |+| `expect( x ).to.include( y )` | `expect( x ).toContain( y )` |+| `expect( fn ).to.throw( /re/ )` | `expect( fn ).toThrow( /re/ )` |+| `expect( x ).to.exist` | `expect( x ).toBeTruthy()` (or `toBeDefined()`) |++### Custom CKEditor Chai assertions (removed)++The old Karma setup auto-loaded custom Chai matchers. They **do not exist** in Vitest:++- `expect( a ).to.equalMarkup( b )` → compare stringified structures directly:+ `expect( _getModelData( model ) ).toEqual( '<paragraph>…</paragraph>' )` (use+ `_getModelData`/`_getViewData`/`_stringifyModel`). The diff is on strings.+- `expect( selection ).to.have.attribute( 'linkHref', 'x' )` → assert explicitly:+ `expect( selection.hasAttribute( 'linkHref' ) ).toBe( true )` and+ `expect( selection.getAttribute( 'linkHref' ) ).toBe( 'x' )`.++## Spies/stubs/mocks: Sinon → `vi`++| Sinon (old) | Vitest (new) |+|-------------|--------------|+| `sinon.spy( obj, 'm' )` | `vi.spyOn( obj, 'm' )` |+| `sinon.stub( obj, 'm' ).returns( v )` | `vi.spyOn( obj, 'm' ).mockReturnValue( v )` |+| `sinon.stub( obj, 'm' ).callsFake( fn )` | `vi.spyOn( obj, 'm' ).mockImplementation( fn )` |+| `sinon.spy()` / `sinon.stub()` | `vi.fn()` |+| `spy.calledOnce` | `expect( spy ).toHaveBeenCalledOnce()` |+| `spy.calledWith( a )` | `expect( spy ).toHaveBeenCalledWith( a )` |+| `spy.called` | `expect( spy ).toHaveBeenCalled()` |+| `spy.callCount` | `expect( spy ).toHaveBeenCalledTimes( n )` |+| `spy.returned( v )` / `spy.args` | `spy.mock.results` / `spy.mock.calls` |+| `sinon.useFakeTimers()` | `vi.useFakeTimers()` (+ `vi.advanceTimersByTime()`, `vi.useRealTimers()`) |+| `clock.tick( n )` | `vi.advanceTimersByTime( n )` |++### The Sinon sandbox helper (remove it)++Legacy tests use `testUtils.createSinonSandbox()` + `testUtils.sinon.*` (from a `_utils/utils`+module). Replace with plain `vi`:++```js+// OLD+testUtils.createSinonSandbox();+it( '…', () => { testUtils.sinon.spy( obj, 'm' ); } );++// NEW — no sandbox; mocks auto-restore, or restore explicitly:+import { vi, afterEach } from 'vitest';+afterEach( () => vi.restoreAllMocks() ); // optional safety+it( '…', () => { vi.spyOn( obj, 'm' ); } );+```++## Environment differences++- Tests run in a **real browser** (Playwright Chromium), not jsdom — real DOM/layout APIs are+ available; code that depended on Karma+webpack globals may need adjusting.+- No `licenseKey` in test editors — `test_setup.js` sets the global GPL key.+- `.svg` imports resolve to the SVG **string** (via the config's `load-svg` plugin), same as+ before.++## Checklist for a migrated file++- [ ] License header kept; explicit `vitest` imports added.+- [ ] All `import … from 'chai'` / `sinon` removed; `.js` extensions on source imports.+- [ ] Chai matchers → Vitest matchers; `equalMarkup`/`.attribute` rewritten with data helpers.+- [ ] Sinon → `vi`; sandbox removed.+- [ ] Editor/command still created in `beforeEach` and **destroyed** in `afterEach` (+ DOM+ cleanup); appended elements removed.+- [ ] `vitest run` passes and `pnpm run coverage` still hits 100% for the package.diff --git a/.claude/skills/ckeditor5-testing/references/patterns.md b/.claude/skills/ckeditor5-testing/references/patterns.mdnew file mode 100644index 0000000000..a729e8d056--- /dev/null+++ b/.claude/skills/ckeditor5-testing/references/patterns.md@@ -0,0 +1,186 @@+# Test patterns (Vitest)++Idiomatic recipes per concern. All examples assume explicit `vitest` imports and a test editor+created in `beforeEach`, destroyed in `afterEach`. Mirror the structure of the feature: a+`*editing` test for schema/conversion/command, a `*ui` test for buttons/dropdowns.++## Setup / teardown++```js+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++let editor, model;++beforeEach( () => {+ return VirtualTestEditor.create( { plugins: [ Paragraph, MyFeature ] } )+ .then( newEditor => { editor = newEditor; model = editor.model; } );+} );++afterEach( () => editor.destroy() ); // + element.remove() for ClassicTestEditor+```++Return the Promise (or use `async`/`await`) so Vitest waits. Default `testTimeout` is 5000 ms.++## Schema++```js+it( 'allows the highlight attribute on $text', () => {+ expect( model.schema.checkAttribute( [ '$root', '$text' ], 'highlight' ) ).toBe( true );+} );++it( 'registers placeholder as an inline object', () => {+ expect( model.schema.isRegistered( 'placeholder' ) ).toBe( true );+ expect( model.schema.isInline( 'placeholder' ) ).toBe( true );+ expect( model.schema.checkChild( [ '$root', '$block' ], 'placeholder' ) ).toBe( true );+} );+```++## Conversion (round-trips)++Test each direction with the data helpers. Upcast = `setData` then read the model; data+downcast = `setData`/`setModelData` then `getData`; editing downcast = read `_getViewData`.++```js+it( 'upcasts <mark> to the highlight attribute', () => {+ editor.setData( '<p>foo <mark>bar</mark></p>' );+ expect( _getModelData( model, { withoutSelection: true } ) )+ .toEqual( '<paragraph>foo <$text highlight="true">bar</$text></paragraph>' );+} );++it( 'data-downcasts the highlight attribute to <mark>', () => {+ _setModelData( model, '<paragraph>foo <$text highlight="true">bar</$text></paragraph>' );+ expect( editor.getData() ).toEqual( '<p>foo <mark>bar</mark></p>' );+} );++it( 'editing-downcasts to <mark> in the editing view', () => {+ _setModelData( model, '<paragraph>foo <$text highlight="true">bar</$text></paragraph>' );+ expect( _getViewData( editor.editing.view, { withoutSelection: true } ) )+ .toEqual( '<p>foo <mark>bar</mark></p>' );+} );+```++For widgets, assert the editing view contains the widget classes/attributes+(`ck-widget`, `contenteditable`) while `getData()` stays clean.++## Commands++Cover `value`, `isEnabled`, and `execute()` — for **collapsed and ranged** selections and for+**schema-disallowed** contexts (where `isEnabled` must be `false`).++```js+describe( 'value', () => {+ it( 'reflects the current selection state', () => {+ _setModelData( model, '<paragraph>[]foo</paragraph>' );+ expect( command.value ).toBe( false );+ _setModelData( model, '<paragraph><$text highlight="true">[]foo</$text></paragraph>' );+ expect( command.value ).toBe( true );+ } );+} );++describe( 'isEnabled', () => {+ it( 'is false where the attribute is disallowed', () => {+ _setModelData( model, '<imageBlock></imageBlock>' ); // selection on object+ expect( command.isEnabled ).toBe( false );+ } );+} );++describe( 'execute()', () => {+ it( 'applies the attribute to a ranged selection', () => {+ _setModelData( model, '<paragraph>[foobar]</paragraph>' );+ command.execute();+ expect( _getModelData( model ) )+ .toEqual( '<paragraph>[<$text highlight="true">foobar</$text>]</paragraph>' );+ } );++ it( 'is undoable as a single step', () => {+ _setModelData( model, '<paragraph>[foobar]</paragraph>' );+ command.execute();+ editor.execute( 'undo' );+ expect( _getModelData( model ) ).toEqual( '<paragraph>[foobar]</paragraph>' );+ } );+} );+```++## UI (component factory, button binding, execute)++Use `ClassicTestEditor` so `editor.ui` exists. Verify the factory produces the right view, the+button reflects command state, and clicking it runs the command.++```js+it( 'registers a ButtonView', () => {+ expect( editor.ui.componentFactory.create( 'highlight' ) ).toBeInstanceOf( ButtonView );+} );++it( 'binds button state to the command', () => {+ const button = editor.ui.componentFactory.create( 'highlight' );+ const command = editor.commands.get( 'highlight' );+ command.isEnabled = false;+ expect( button.isEnabled ).toBe( false );+} );++it( 'executes the command on click and refocuses the editor', () => {+ const button = editor.ui.componentFactory.create( 'highlight' );+ const executeSpy = vi.spyOn( editor, 'execute' );+ const focusSpy = vi.spyOn( editor.editing.view, 'focus' );+ button.fire( 'execute' );+ expect( executeSpy ).toHaveBeenCalledWith( 'highlight' );+ expect( focusSpy ).toHaveBeenCalledOnce();+} );+```++For dropdowns, `create()` the component, inspect `dropdownView.listView`/`buttonView`, fire+`execute` on items, and assert the command ran with the expected `value`/`commandParam`.++## Keystrokes++```js+it( 'executes the command on Ctrl+Alt+H', () => {+ const spy = vi.spyOn( editor, 'execute' );+ const wasHandled = editor.keystrokes.press( {+ keyCode: keyCodes.h, ctrlKey: true, altKey: true,+ preventDefault: () => {}, stopPropagation: () => {}+ } );+ expect( spy ).toHaveBeenCalledWith( 'highlight' );+ expect( wasHandled ).toBe( true );+} );+```++(`keyCodes` from `@ckeditor/ckeditor5-utils`.) For view-document keydown handlers, fire on+`editor.editing.view.document`.++## Events & observables++```js+it( 'fires change:value', () => {+ const spy = vi.fn();+ command.on( 'change:value', spy );+ _setModelData( model, '<paragraph><$text highlight="true">[]x</$text></paragraph>' );+ expect( spy ).toHaveBeenCalled();+} );+```++## Spies, mocks, timers++- `vi.spyOn( obj, 'method' )` — wrap and observe (optionally `.mockImplementation(...)`).+- `vi.fn()` — standalone mock callback.+- `vi.useFakeTimers()` / `vi.advanceTimersByTime()` / `vi.useRealTimers()` — for debounced or+ timeout-based code; restore in `afterEach`.+- `vi.stubGlobal( 'name', value )` — stub a global. Prefer `vi.restoreAllMocks()` in `afterEach`+ if you don't rely on auto-restore.++## Errors / warnings++```js+it( 'throws on invalid config', () => {+ expect( () => editor.something() ).toThrow( /my-feature-error/ );+} );+```++For `CKEditorError`, match the error id substring.++## Reaching 100% coverage++The suite gates `src/**` at 100% (excluding `index.ts`, `augmentation.ts`, `*config.ts`). Every+branch needs a test: both states of each boolean, each schema-allowed/disallowed path, collapsed+vs. ranged selection, and error/guard branches. Run `pnpm run coverage` (headless + v8) and read+the HTML report to find uncovered lines before pushing.diff --git a/.claude/skills/ckeditor5-testing/references/running-and-config.md b/.claude/skills/ckeditor5-testing/references/running-and-config.mdnew file mode 100644index 0000000000..54870553f7--- /dev/null+++ b/.claude/skills/ckeditor5-testing/references/running-and-config.md@@ -0,0 +1,113 @@+# Running tests & configuration++## Per-package scripts++Each package's `package.json` defines:++| Script | Command | Purpose |+|--------|---------|---------|+| `test` | `vitest run` | One-shot run. |+| `test:debug` | `vitest` | Watch mode (re-runs on change; interactive). |+| `test:headless` | `vitest run --browser.headless` | Headless browser run (CI-like). |+| `coverage` | `pnpm run test:headless --coverage` | Headless + coverage (100% gate). |++Useful ad-hoc invocations from a package directory:++```bash+vitest run highlightcommand # filter by filename substring+vitest run -t "execute" # filter by test name (-t/--testNamePattern)+vitest --browser.headless # watch, headless+vitest run --coverage # coverage for this package+```++## Root runner (dev-tools wrapper)++The root `pnpm run test` calls `ckeditor5-dev-tests-run-automated` (from+`@ckeditor/ckeditor5-dev-tests`), which orchestrates Vitest across packages. It selects packages+as Vitest **projects** by short name and supports the legacy `--files` patterns.++```bash+pnpm run test # whole suite+pnpm run test -- --files=highlight # one package (short name)+pnpm run test -- -c --files=engine # with coverage+pnpm run test -- -cw --files=engine/view/,typing # coverage + watch, sub-dir + package+```++`--files` (alias `-f`) patterns (also used by manual tests):++| Pattern | Meaning |+|---------|---------|+| `core` / `ckeditor5-core` | One package (short or full name). |+| `editor-*` | Glob over package names. |+| `!core` / `!(core\|engine)` | Exclude one/several packages. |+| `engine/view/` | A sub-directory under a package's `tests/`. |+| `basic-styles/bold*` | Filename glob within a package. |+| `a,b,c` | Comma-separated sum of patterns. |++Other documented args (legacy Karma names; some map onto Vitest via the wrapper): `--watch`/`-w`,+`--coverage`/`-c`, `--source-map`/`-s`, `--verbose`/`-v`, `--browsers`, `--port`,+`--identity-file`/`-i` (license file for closed-source features). Running tests for the whole+monorepo root (no package) is not supported — tests belong to a package's `tests/` dir.++## Vitest configuration++Root `vitest.config.ts` exports two factories; **package configs should not configure Vitest+from scratch** — they call the factory:++```ts+// packages/ckeditor5-<name>/vitest.config.ts+import type { ViteUserConfig } from 'vitest/config';+import { createVitestConfig } from '../../vitest.config';++export default createVitestConfig( { name: '<short-package-name>' } );+```++`createVitestConfig({ name, ...overrides })` provides the shared baseline; `name` is the short+package name used by `--project <short-name>`. Any extra props are merged into `test` as+overrides. The baseline sets:++- `globals: true`; `include: [ 'tests/**/*.{js,ts}' ]`;+ `exclude: [ '**/_utils', '**/fixtures', '**/manual' ]`.+- `setupFiles: [ test_setup.js ]` — sets `globalThis.CKEDITOR_GLOBAL_LICENSE_KEY = 'GPL'`.+- `testTimeout: 5000`.+- **Browser mode** via `@vitest/browser-playwright`, Chromium (`channel: 'chrome'`), viewport+ 1920×1080, `screenshotFailures: false`.+- **Coverage** (`v8`): `include: [ 'src/**' ]`, excludes `src/index.ts`, `src/augmentation.ts`,+ `src/**/*config.ts`; `thresholds: { 100: true }`; reporters `text`, `html`.+- A `load-svg` plugin so `import icon from './x.svg'` yields the SVG string.++`createWorkspaceConfig( projects )` (default export) wires the root run across+`packages/*/vitest.config.ts` and the combined coverage (`html`, `json`, `lcovonly` →+`coverage-vitest/`). Because tests run in a **real browser**, DOM APIs are available directly+(no jsdom).++## Manual tests++Human-run smoke tests, served by `pnpm run manual` (default `http://localhost:8125`). A manual+test = **three files** sharing a base name in a `tests/manual/` directory (which must sit at the+root of `tests/`, e.g. `tests/manual/view/focus.js`, not `tests/view/manual/focus.js`):++- `<name>.md` — the steps to perform and what to verify.+- `<name>.js`/`.ts` — sets up an editor (`window.editor = editor;`).+- `<name>.html` — the markup (fragment is fine; merged into a template).++```js+import { ClassicEditor, Essentials, Paragraph } from 'ckeditor5';+ClassicEditor.create( { attachTo: document.querySelector( '#editor' ),+ licenseKey: 'GPL', plugins: [ Essentials, Paragraph ] } )+ .then( editor => { window.editor = editor; } );+```++`pnpm run manual` options: `--files`, `--language`, `--additional-languages`, `--debug`/`-d`+(e.g. `--debug engine` enables `// @if CK_DEBUG_ENGINE //` lines; on by default), `--port`,+`--disable-watch`. Add manual-test dependencies to the package `devDependencies`. Vitest+excludes `**/manual`, so manual tests never run as units. `pnpm run manual:verify` crawls the+manual-test pages headlessly to ensure they at least open without errors.++## Memory-leak tests++`pnpm run test:memory` builds a browser bundle and runs create/destroy cycles per editor in+headless Chromium, reporting **Baseline / Growth / Tail Growth / Status** (status `OK` when+Growth and Tail Growth stay under threshold). Options: `--editor <Name>` (repeatable; defaults+to Balloon/Classic/Decoupled/Inline/MultiRoot), `--html <file>` (from `scripts/memory/assets`),+`--no-build` (reuse existing assets).diff --git a/.claude/skills/ckeditor5-testing/references/test-utilities.md b/.claude/skills/ckeditor5-testing/references/test-utilities.mdnew file mode 100644index 0000000000..91e5be1b20--- /dev/null+++ b/.claude/skills/ckeditor5-testing/references/test-utilities.md@@ -0,0 +1,92 @@+# Test utilities & data helpers++The building blocks for editor tests: lightweight test editors, shared `_utils`, and the+model/view stringify-parse helpers.++## Test editors (pick the lightest that works)++All live in `@ckeditor/ckeditor5-core/tests/_utils/` and expose a static async `create()`+returning a Promise. Import with the explicit `.js` extension.++| Editor | Pipelines | Use when |+|--------|-----------|----------|+| `ModelTestEditor` | Full **data** pipeline; **editing pipeline disabled** (no view rendering). Creates the main model root. | Testing pure model logic / commands that only read/write the model. Cheapest. |+| `VirtualTestEditor` | Full **data + engine** pipeline, **no DOM rendering**. Creates the main model root. | Testing engine behavior, conversion, schema, features — without a real editable element. The default for most feature tests. |+| `ClassicTestEditor` | A simplified **full classic editor** with UI mounted into a real element (`ElementApiMixin`, `BoxedEditorUIView`, `InlineEditableUIView`). | Testing UI (toolbar buttons, balloons), DOM interaction, focus, or anything needing `editor.ui`. |++```js+import { ModelTestEditor } from '@ckeditor/ckeditor5-core/tests/_utils/modeltesteditor.js';+import { VirtualTestEditor } from '@ckeditor/ckeditor5-core/tests/_utils/virtualtesteditor.js';+import { ClassicTestEditor } from '@ckeditor/ckeditor5-core/tests/_utils/classictesteditor.js';++// Model only:+editor = await ModelTestEditor.create(); // then register schema yourself++// Engine + plugins, no DOM:+editor = await VirtualTestEditor.create( { plugins: [ Paragraph, MyFeature ] } );++// Full UI in a real element (remember to create AND remove the element):+editorElement = document.createElement( 'div' );+document.body.appendChild( editorElement );+editor = await ClassicTestEditor.create( editorElement, {+ plugins: [ Paragraph, MyFeatureUI, Heading ],+ toolbar: [ 'myButton' ]+} );+```++Teardown matters: `await editor.destroy()` in `afterEach`, and `editorElement.remove()` if you+appended one. Tests don't pass a `licenseKey` — `test_setup.js` sets the global GPL key.++## Other `_utils` helpers (core)++- `ArticlePluginSet` (`articlepluginset.js`) — a glue plugin bundling a typical article editor+ (Essentials, Paragraph, Heading, Bold/Italic, List, Link, BlockQuote, Image+toolbar/caption,+ Table+toolbar, MediaEmbed, Indent, Autoformat). Drop it into `plugins: [ ArticlePluginSet ]`+ to get a realistic editor without listing everything.+- `removeEditorBodyOrphans()` (`cleanup.js`) — removes leftover `.ck-body-wrapper` elements+ from the DOM; use after tests that intentionally crash editors (orphaned body collections).+- `generateLicenseKey( options )` (`generatelicensekey.js`) — builds license keys for license+ tests (`isExpired`, `expExist`, `licenseType`, `distributionChannel`, …).+- `testUtils` / `testUtils.createSinonSandbox()` (`utils.js`) — **legacy Sinon helper**. In+ Vitest, don't use it; use `vi.spyOn`/`vi.fn` (auto-restored, or `vi.restoreAllMocks()` in+ `afterEach`). See `migration-from-karma.md`.++Packages also keep their own `tests/_utils/` (excluded from the run by config) for+feature-specific fixtures and helpers — follow the local conventions of the package you edit.++## Model & view data helpers++From `@ckeditor/ckeditor5-engine` (the `dev-utils` model/view modules). They stringify/parse+engine structures and are the backbone of assertions. **Test/debug only — never in `src/`.**++Model:+- `_setModelData( model, string )` — replace the document content + selection from a string.+- `_getModelData( model[, options] )` — serialize current model + selection to a string.+- `_stringifyModel( node[, selectionOrRange] )` / `_parseModel( string, schema )` — pure+ serialize/parse without touching a document.++View:+- `_getViewData( view[, options] )` / `_setViewData( view, string )` — same for a view document+ (e.g. `editor.editing.view`).+- `_stringifyView( node )` / `_parseView( string )`.++```js+import { _setModelData, _getModelData, _getViewData } from '@ckeditor/ckeditor5-engine';++_setModelData( model, '<paragraph>foo[]bar</paragraph>' );+expect( _getModelData( model ) ).toEqual( '<paragraph>foo[]bar</paragraph>' );+expect( _getViewData( editor.editing.view ) ).toEqual( '<p>foo{}bar</p>' );+```++### Selection / range string syntax++- `[` … `]` — a position/range **anchored in an element** (also a collapsed `[]` caret).+- `{` … `}` — a position/range **anchored inside a text node**.+- A mixed range can use both ends, e.g. `<p>{Foo]<b>Bar</b></p>` starts in the `Foo` text node+ and ends in `<p>` at offset 1.+- Text attributes serialize as `<$text key="value">text</$text>`; selection attributes appear+ on the collapsed selection.++`_getModelData`/`_getViewData` options of note: `withoutSelection: true` to omit the selection+markers; `rootName` to target a non-default root. Check the `dev-utils/model` and+`dev-utils/view` API for the full option list.