test(edit): cover the live-sync wiring that left EditTab

stores/edit-live.ts was untested — it is the block that used to sit in
EditTab's onMount, where nothing measured it. As a .ts module it counts, and
SonarCloud's new-code gate failed at 73.6 % (80 % required).

edit-live.test.ts drives it with wxt/browser mocked to hand-fired event
emitters and a hand-fired frame: one patch per frame, a parentless created
node ignored, nothing patched during Chrome's own import and one re-read
after it, a re-read on a wholesale reorder, and a teardown that detaches every
listener and drops what was queued. connectLive takes the batcher's scheduler
as an optional argument for that.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Fable 5.2 committed 2026-11-10 11:18:58 +07:00
1 parent 0bd2aabbf2
commit d61318aed7
4 files changed
+177 -4

No files matched your search

+2 -1
View File
@@ -130,7 +130,8 @@ bookmarkmagic/
│ │ │ ├── import-session.svelte.ts
│ │ │ ├── edit-view.svelte.ts # #edit: what the tree shows (03 §3)
│ │ │ ├── edit-commands.svelte.ts # #edit: single-item writes, extends the view
│ │ │ └── edit-session.svelte.ts # #edit: duplicates + bulk commands, extends both
│ │ │ ├── edit-session.svelte.ts # #edit: duplicates + bulk commands, extends both
│ │ │ └── edit-live.ts # #edit: subscribes a session to the browser's events (03 §3)
│ │ ├── i18n/ # runtime UI i18n (see 07_I18N.md)
│ │ │ ├── index.svelte.ts
│ │ │ ├── format.ts # pure Intl number/date helpers (07 §3)
+8
View File
@@ -236,6 +236,14 @@ them is tested where it lives:
alone; the move itself by Chrome's index rule, refused for a root, a managed
node and while busy, one at a time, and returning the row's place among the
siblings on screen — under a search too, where it passes hidden items.
- **`stores/edit-live.test.ts`** (v1.2.1) — the wiring that used to sit
untested in `EditTab`'s `onMount`, with `wxt/browser` mocked to seven
hand-fired event emitters and a hand-fired frame: a frame's events land as
one patch; a created node with no parent is ignored; nothing is patched
during Chrome's own import, and its end re-reads once; a wholesale reorder
re-reads; teardown detaches every listener and drops what was queued.
SonarCloud's new-code gate is what asked for it — moving code out of a
component makes it count.
- **`components/focus-heading.test.ts`** — since v1.2.1 also
`focusOwningTree`: a click on a row's control hands focus to the tree it
sits in, and does nothing outside one.
+11 -3
View File
@@ -11,14 +11,22 @@
*/
import { subscribe } from '../browser/bookmarks';
import { toEditNode } from '../edit/edit-node';
import { createBatcher } from '../edit/live-sync';
import { type BatcherOptions, createBatcher } from '../edit/live-sync';
import type { EditSession } from './edit-session.svelte';
/** @returns the teardown: unsubscribe, and drop anything still queued. */
export function connectLive(session: EditSession): () => void {
/**
* @param schedule when a batch is flushed — the next frame by default; tests
* pass one they fire by hand.
* @returns the teardown: unsubscribe, and drop anything still queued.
*/
export function connectLive(
session: EditSession,
schedule?: BatcherOptions['schedule'],
): () => void {
const batcher = createBatcher({
onFlush: session.applyLiveEvents,
onBurst: () => void session.load(),
...(schedule === undefined ? {} : { schedule }),
});
let importing = false;
const unsubscribe = subscribe({
+156
View File
@@ -0,0 +1,156 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { FakeBookmarks } from '../../helpers/fake-bookmarks';
/**
* The #edit tab's live sync, wired to a real session — docs/03 §3, docs/05 §11.
*
* `wxt/browser` is mocked module-wide (fakeBrowser's bookmarks events are
* "not implemented"): each event is an emitter the test fires by hand, and so
* is the frame the batcher waits for.
*/
function emitter() {
const listeners = new Set<(...args: never[]) => void>();
return {
addListener: (fn: (...args: never[]) => void) => listeners.add(fn),
removeListener: (fn: (...args: never[]) => void) => listeners.delete(fn),
fire: (...args: unknown[]) => {
// SAFETY: the test fires each event with the arguments Chrome gives it.
for (const fn of listeners) (fn as (...a: unknown[]) => void)(...args);
},
get size() {
return listeners.size;
},
};
}
const events = {
onCreated: emitter(),
onRemoved: emitter(),
onChanged: emitter(),
onMoved: emitter(),
onChildrenReordered: emitter(),
onImportBegan: emitter(),
onImportEnded: emitter(),
};
vi.mock('wxt/browser', () => ({ browser: { bookmarks: events } }));
const { connectLive } = await import('@/lib/stores/edit-live');
const { EditSession } = await import('@/lib/stores/edit-session.svelte');
/** A scheduler the test fires by hand — the batcher's "next frame". */
function manual() {
let pending: (() => void) | undefined;
return {
schedule: (run: () => void) => {
pending = run;
return () => {
pending = undefined;
};
},
fire: () => {
const run = pending;
pending = undefined;
run?.();
},
};
}
let fake: FakeBookmarks;
let session: InstanceType<typeof EditSession>;
let frame: ReturnType<typeof manual>;
let disconnect: () => void;
const barTitles = (): (string | undefined)[] =>
(session.roots[0]?.children ?? []).map((node) => node.title);
beforeEach(async () => {
fake = new FakeBookmarks();
fake.seed('1', { title: 'a', url: 'https://a.example/' });
session = new EditSession(
{
getRootChildren: async () => (await fake.getTree())[0]?.children ?? [],
getChildren: async (id: string) => fake.children(id),
create: fake.create,
update: fake.update,
move: fake.move,
remove: fake.remove,
removeTree: fake.removeTree,
},
() => 'en',
);
await session.load();
frame = manual();
disconnect = connectLive(session, frame.schedule);
});
describe('connectLive', () => {
it('patches the tree with a frame’s worth of events at once', () => {
const [a] = session.roots[0]?.children ?? [];
events.onCreated.fire('90', {
id: '90',
parentId: '1',
index: 1,
title: 'b',
url: 'https://b.example/',
});
events.onChanged.fire(a?.id, { title: 'A' });
// Nothing yet: one patch per frame, not one per event.
expect(barTitles()).toEqual(['a']);
frame.fire();
expect(barTitles()).toEqual(['A', 'b']);
events.onMoved.fire('90', { parentId: '1', index: 0, oldParentId: '1', oldIndex: 1 });
frame.fire();
expect(barTitles()).toEqual(['b', 'A']);
events.onRemoved.fire('90');
frame.fire();
expect(barTitles()).toEqual(['A']);
disconnect();
});
it('ignores a created node with no parent — the synthetic root is not a row', () => {
events.onCreated.fire('0', { id: '0', title: '' });
frame.fire();
expect(session.roots).toHaveLength(2);
disconnect();
});
it('takes no per-node events during Chrome’s own import, then re-reads once', async () => {
events.onImportBegan.fire();
// What Chrome's importer wrote, which the tab must not patch node by node.
fake.seed('1', { title: 'imported', url: 'https://i.example/' });
events.onCreated.fire('91', {
id: '91',
parentId: '1',
index: 1,
title: 'imported',
url: 'https://i.example/',
});
frame.fire();
expect(barTitles()).toEqual(['a']);
events.onImportEnded.fire();
frame.fire();
await vi.waitFor(() => expect(barTitles()).toEqual(['a', 'imported']));
disconnect();
});
it('re-reads the tree when the browser reorders a folder wholesale', async () => {
fake.seed('1', { title: 'z', url: 'https://z.example/' });
events.onChildrenReordered.fire('1');
frame.fire();
await vi.waitFor(() => expect(barTitles()).toEqual(['a', 'z']));
disconnect();
});
it('detaches every listener on teardown, and drops what was still queued', () => {
expect(Object.values(events).every((event) => event.size === 1)).toBe(true);
events.onRemoved.fire(session.roots[0]?.children?.[0]?.id);
disconnect();
frame.fire();
expect(barTitles()).toEqual(['a']);
expect(Object.values(events).every((event) => event.size === 0)).toBe(true);
});
});