Skip to content

Simulating user input

The lib bag every callback receives provides helpers that inject trusted input at the Chromium level — the kind of event only the browser or the OS normally produces. On desktop they go through Electron’s webContents.sendInputEvent; on Android, through the WebView’s own debugger. See On mobile for what changes there.

The in-page alternatives quietly give false results:

  • dispatchEvent(new KeyboardEvent(...)) and new MouseEvent(...) are untrusted (isTrusted: false), so CodeMirror ignores the keystroke and :hover never takes effect. Obsidian’s own listeners gate on e.isTrusted too, so a dispatched click does not merely look different — it does nothing at all, while the test still passes whatever weaker assertion it makes.
  • execCommand('insertText') mutates the selection even when the editor is not focused, which turns a real focus bug into a passing test.

The trusted helpers flow through the real input pipeline, so text lands only if the editor genuinely holds focus, and :hover rules genuinely apply. The element and editor arguments are live renderer DOM nodes — the callback already runs in the renderer, so nothing is serialized.

Helper Purpose
typeIntoEditor({ editor, text }) Focuses editor (caret to end), types text as trusted key events, then polls until the document reflects it.
composeIntoEditor({ editor, text, chunking }) Focuses editor (caret to end) and enters text through IME composition, one composition per 'word' (default) or 'character', then polls until the document reflects it.
setComposition({ text, selectionStart, selectionEnd, window }) Opens an IME composition in the focused element or replaces the open one’s text, and leaves it open. An empty text cancels it. Does not poll.
commitComposition({ text, window }) Commits the open composition as text. With none open, inserts text with no composition events. Does not poll.
pressKey({ key, modifiers, window }) Presses key with optional modifiers as a trusted keyDown→char→keyUp on the DOM-focused element (fires keydown/keypress/beforeinput/input/keyup). Does not poll — pair with waitUntil.
hoverElement({ element }) Moves the pointer to element’s center, then polls until element.matches(':hover'). Throws if it never does.
unhoverElement({ element }) Moves the pointer just outside element’s bounding box, then polls until it no longer matches :hover. Throws if it still does.
clickElement({ element, button, modifiers }) Clicks element’s center with optional button / modifiers, so Chromium synthesizes a real click (or contextmenu). Does not poll — pair with waitUntil.
moveMouse({ x, y, window }) Low-level primitive: injects one trusted pointer move at the given web-contents DIP coordinates. Does not poll. Desktop only.
clickMouse({ x, y, button, modifiers, window }) Low-level primitive: one trusted mouseMove → mouseDown → mouseUp at the given web-contents DIP coordinates. Does not poll.
dragMouse({ from, to, steps, button, modifiers, window }) Trusted drag: mouseDown at from, steps held-button moves (default 10, one per frame) along the line, mouseUp at to. Does not poll. Desktop only.
// Type into the active editor — only succeeds if the editor truly holds focus.
const typed = await evalInObsidian({
callback: async ({ app, lib: { typeIntoEditor }, obsidianModule }) => {
const view = app.workspace.getActiveViewOfType(obsidianModule.MarkdownView);
const editor = view?.editor;
if (!editor) {
return null;
}
await typeIntoEditor({ editor, text: 'Hello, world!' });
return editor.getValue();
}
});

Key presses use Obsidian’s Modifier names, where 'Mod' is Cmd on macOS and Ctrl everywhere else. A key press has no universal effect, so pair it with waitUntil to await the outcome you expect:

await evalInObsidian({
callback: async ({ app, lib: { pressKey, waitUntil }, obsidianModule }) => {
const editor = app.workspace.getActiveViewOfType(obsidianModule.MarkdownView)?.editor;
editor?.focus();
pressKey({ key: 'Enter', modifiers: ['Shift'] }); // synchronous; soft line break
await waitUntil({ predicate: () => (editor?.getValue().includes('\n') ?? false) });
}
});

Hovering gives you the genuine hovered appearance — real theme var() values, real compositing:

await evalInObsidian({
callback: async ({ lib: { hoverElement, unhoverElement } }) => {
const bar = document.querySelector<HTMLElement>('.minimized-modal-bar');
if (!bar) {
return;
}
await hoverElement({ element: bar });
// ...assert the hovered appearance...
await unhoverElement({ element: bar });
}
});

Both throw rather than resolving quietly when the state they poll for never arrives, because a hover that never landed reads to an assertion exactly like one that did — the element still has a base style, and the assertion passes on it while proving nothing. hoverElement throws when the element never matches :hover, most often because its center belongs to something on top of it or the element moved after its box was read. unhoverElement throws when the element still matches :hover, which is what an element spanning the full viewport does: there is no point outside its box to move to, so use moveMouse to a known empty coordinate instead.

Clicking splits the same way hovering does. clickElement({ element }) is the element-relative one — it clicks the element’s center. clickMouse({ x, y }) is the coordinate primitive underneath it, for a point that is no element’s center: the markdown editor’s margin, for instance, lies inside cm.scrollDOM but outside .cm-sizer, so nothing you can query has a center on it. Both accept button ('left', 'middle', 'right') and modifiers in Obsidian’s Modifier names — the same mapping pressKey uses, so 'Mod' cannot mean two different things — and both are synchronous, so pair them with waitUntil to await the outcome:

await evalInObsidian({
callback: async ({ app, lib: { clickElement, clickMouse, waitUntil }, obsidianModule }) => {
const view = app.workspace.getActiveViewOfType(obsidianModule.MarkdownView);
const action = view?.containerEl.querySelector<HTMLElement>('.view-action');
const sizer = view?.editor.cm.scrollDOM.querySelector<HTMLElement>('.cm-sizer');
if (!view || !action || !sizer) {
return;
}
clickElement({ element: action }); // synchronous; a real trusted left click
await waitUntil({ predicate: () => Boolean(document.querySelector('.menu')) });
document.querySelector('.menu')?.remove();
// The editor margin: inside `cm.scrollDOM`, outside `.cm-sizer` — reachable only by coordinates.
const scrollRect = view.editor.cm.scrollDOM.getBoundingClientRect();
const sizerRect = sizer.getBoundingClientRect();
clickMouse({
button: 'right',
x: (scrollRect.left + sizerRect.left) / 2,
y: sizerRect.top + 20 // just below the top edge of the text
});
await waitUntil({
message: 'the margin context menu did not open',
predicate: () => Boolean(document.querySelector('.menu'))
});
}
});

A drag is what a click cannot be. Obsidian starts a pointer drag only once the pointer has moved a few pixels with the button down, so a handler such as the canvas’s node connection handle never starts from clickMouse. dragMouse({ from, to }) sends the button down at from, then moves to to in steps frames with the button held (each move reports it in buttons, which is what tells a drag handler the drag is still on), and releases at to. This opens the canvas’s connection-drop menu, the one with Add card:

await evalInObsidian({
callback: async ({ lib: { dragMouse, moveMouse, waitUntil } }) => {
const node = document.querySelector<HTMLElement>('.canvas-node');
if (!node) {
return;
}
// The connection handles belong to the node under the pointer.
const nodeRect = node.getBoundingClientRect();
await moveMouse({ x: nodeRect.left + nodeRect.width / 2, y: nodeRect.top + nodeRect.height / 2 });
const handle = document.querySelector<HTMLElement>('.canvas-node-connection-point[data-side="right"]');
const handleRect = handle?.getBoundingClientRect();
if (!handleRect) {
return;
}
const from = { x: handleRect.left + handleRect.width / 2, y: handleRect.top + handleRect.height / 2 };
await dragMouse({ from, to: { x: from.x + 150, y: from.y } });
await waitUntil({ message: 'the connection-drop menu', predicate: () => Boolean(document.querySelector('.menu')) });
}
});

Keep the drop point clear of the canvas edge: a drag that comes within 30px of it pans the canvas.

A right click opens a real context menu, and it stays open. A suite that drives one must close it — menu.hide() from your own handler, or removing the leftover .menu element — before the next test, or the menu still on screen swallows the click that test makes.

Key presses never open a composition, but much real input arrives as one: Gboard keeps the current word in a composition, CJK input methods compose every word, and fcitx and ibus on Wayland can send each character as its own. While a composition is open, CodeMirror sets view.composing, and a plugin that reacts to typing has to wait for it to end.

composeIntoEditor covers the usual shapes. With chunking: 'word', each word grows one character at a time and its trailing whitespace is part of the commit, so 'brb ' commits as 'brb '. To type the separator separately, compose 'brb' and follow it with pressKey.

setComposition and commitComposition hold a composition open, so a test can assert on that state:

await evalInObsidian({
callback: async ({ app, lib: { commitComposition, setComposition, waitUntil }, obsidianModule }) => {
const editor = app.workspace.getActiveViewOfType(obsidianModule.MarkdownView)?.editor;
if (!editor) {
throw new Error('No active Markdown view.');
}
editor.focus();
await setComposition({ text: 'brb' });
await waitUntil({ predicate: () => editor.getValue().endsWith('brb') });
// `editor.cm.composing` is true here: the plugin must not rewrite the text yet.
await commitComposition({ text: 'brb ' });
}
});

The commit’s compositionend reports isTrusted: false on desktop, while the rest of the composition reports true, so do not filter that event on isTrusted.

Every Obsidian window, the main one and each popout, is its own Electron web contents, so trusted input sent to one never reaches another. The helpers pick the window like this:

  • clickElement, hoverElement and unhoverElement use the window that owns element, and typeIntoEditor and composeIntoEditor use the window that owns editor. An element or editor in a popout is driven in that popout with nothing extra to pass.
  • pressKey, moveMouse, clickMouse, dragMouse, setComposition and commitComposition take an optional window, and default to the main window. A key goes to the DOM-focused element of the window you name, and coordinates are in that window’s viewport.
await evalInObsidian({
callback: async ({ app, lib: { pressKey, waitUntil } }) => {
const leaf = app.workspace.openPopoutLeaf();
const popoutWindow = leaf.getContainer().win;
await waitUntil({ predicate: () => popoutWindow.document.readyState === 'complete' });
// Focus something in the popout first, then press the key there.
await pressKey({ key: 'Escape', window: popoutWindow });
}
});

Pass a top-level Obsidian window. An iframe’s window has no Electron bridge, so the helpers throw rather than sending the input to the main window instead. On mobile there are no popouts: naming the main window is accepted, so a suite that passes element.win runs on both platforms, and naming any other window throws.

waitUntil({ predicate }) polls until an asynchronous effect settles — a view opens, a DOM node appears, a setting applies. Because a callback is serialized with toString() and cannot import modules, it cannot reuse a poll helper from a library; waitUntil is the injected replacement for the loop you would otherwise hand-roll in every closure.

The predicate may be synchronous or asynchronous (it is awaited on each poll). It is checked immediately, then re-checked every intervalInMilliseconds until it returns truthy or timeoutInMilliseconds elapses, at which point the returned promise rejects (the error includes message when given).

Option Purpose Default
predicate Condition to poll; sync or async, awaited each check. —
intervalInMilliseconds Delay between polls. 50
timeoutInMilliseconds Max time to wait before rejecting. 5000
message Detail appended to the timeout error message. —
const value = await evalInObsidian({
callback: async ({ app, lib: { waitUntil }, obsidianModule }) => {
await waitUntil({
message: 'no active Markdown view',
predicate: () => Boolean(app.workspace.getActiveViewOfType(obsidianModule.MarkdownView))
});
return app.workspace.getActiveViewOfType(obsidianModule.MarkdownView)?.editor.getValue() ?? null;
}
});

For waits longer than one eval may take, use pollInObsidian instead.

These helpers work on Android as well, but not all of them, and not identically. Every one of them returns a promise — await it. A missing await used to be harmless on desktop; on mobile the injection is a round-trip to the test host, so without it your assertion runs before the input has landed.

Helper On Android
clickElement / clickMouse (default or 'left') A tap.
clickMouse({ button: 'right' }) A long-press — the gesture that opens Obsidian Mobile’s context menu.
clickMouse({ button: 'middle' }) Throws. Touch has no middle button.
pressKey / typeIntoEditor Work. Named keys (Enter, Escape, Tab, Backspace, Delete, arrows) and single printable characters; any other multi-character name throws.
composeIntoEditor / setComposition / commitComposition Sent to the WebView over CDP, so a real keyboard’s own InputConnection path is not exercised. The WebView can end an open composition on its own, committing its text; the harness then sends only what is still missing, so the text lands once. editor.cm.composing can therefore read false before the commit.
moveMouse / hoverElement / unhoverElement Throw. Touch input has no hover state.
dragMouse Throws. It injects mouse events; a touch drag would be a gesture of its own, and none is implemented.

The ones that throw do so deliberately rather than doing nothing quietly: a hover that silently no-ops would leave a test asserting against a state that never existed, which is precisely the false-confidence problem trusted input exists to solve. Branch on Platform.isDesktopApp when a suite runs on both.

Coordinates on mobile are CSS pixels in the WebView’s own viewport — the same numbers getBoundingClientRect() reports — so there is no device-pixel-ratio conversion to do.

A long-press on mobile is a real platform gesture, and it must land inside the viewport: aimed outside it, the injection fails with Position out of bounds rather than pressing nothing quietly. So being laid out is not enough — an element in a sidebar that is still sliding open already has its full width at a negative left, and its centre point is off-screen. Wait for the element’s centre to be inside the viewport before pressing it:

await lib.waitUntil({
predicate: () => {
const rect = element.getBoundingClientRect();
return rect.left + rect.width / 2 >= 0 && rect.top + rect.height / 2 >= 0;
}
});
await lib.clickElement({ button: 'right', element });