#3170·midscene

[Feature]: Support asserting transient toast notifications via DOM-cached capture (not screenshot)

Author: will3602099Created Sep 21, 2026Updated Sep 21, 2026

What problem does this feature solve?

Problem

When asserting against transient toast/snackbar notifications (e.g. Element UI ElMessage, Antd message, custom <div class="toast">), screenshot/vision-based assertion is unreliable because:

  1. Toasts auto-dismiss in 2–3s; by the time the model captures + reasons, the element has detached from the DOM.
  2. Small text + translucent/animated background → poor OCR reliability.
  3. No stable selector to locate against; positioning floats.

This makes "assert the toast says X" a common failure for E2E flows (submit form → expect success toast).

Current workaround

aiWaitFor with a long timeout helps in DOM/bridge mode, but in pure screenshot mode there's no reliable path, and even in DOM mode the short-lived lifecycle means the element is often gone before assertion runs.

Proposal

Add a DOM-cached toast assertion API, e.g.

typescript
await aiAssertToast('Saved successfully', { type: 'success', timeout: 5000 });
await aiWaitForToast(/created/i);

Implementation idea (framework-agnostic, black-box):

  • Inject a MutationObserver on document.body that accumulates text + role (success/error/warning) of matched toast nodes into a window-level buffer, persisting briefly after the node detaches.
  • Assertion queries the buffer within timeout, so a toast that already disappeared is still assertable.

This keeps Midscene black-box (no coupling to any UI library) while removing the timing dependency that breaks screenshot assertions.

Willing to contribute

If maintainers are open to the direction, I'd like to submit a PR. Would prefer guidance on:

  • preferred API shape (aiAssertToast vs extending aiAssert with options)
  • where the observer injection should live in the architecture

What does the proposed API look like?

Below is a concrete API design — three functions covering assert, wait, and inspect, so simple cases stay one-liner and complex cases are still expressive.

Type signatures

typescript
type ToastMatcher = string | RegExp | ((text: string) => boolean);

type ToastType = 'success' | 'error' | 'warning' | 'info' | 'loading' | 'default';

interface ToastRecord {
  text: string;          // accumulated text content of the toast node
  type: ToastType;       // resolved role, see detection rules below
  ts: number;            // when it appeared (performance.now())
  detachedAt?: number;   // when it left the DOM (still in buffer until TTL)
}

interface AssertToastOptions {
  type?: ToastType;          // assert role too
  timeout?: number;          // ms, default 5000
  mode?: 'exact' | 'includes' | 'regex'; // default 'includes'
  count?: number;            // assert it appeared N times, default 1
}

interface WaitForToastOptions {
  timeout?: number;          // ms, default 5000
  type?: ToastType;
}

Three entry points

typescript
// 1. Assert + wait in one call — the 90% case.
//    Resolves once a matching toast is captured within timeout,
//    rejects with a clear diff message otherwise.
await aiAssertToast('Saved successfully', { type: 'success' });
await aiAssertToast(/created/i, { mode: 'regex', timeout: 8000 });

// 2. Wait-only, no assertion — for flows where you just need to
//    synchronize before the next step.
await aiWaitForToast({ type: 'error' });

// 3. Inspect the buffered history — for multi-toast / ordering checks.
const toasts: ToastRecord[] = await aiGetToasts({ sinceLastCall: true });
expect(toasts.find(t => t.type === 'error')).toBeDefined();

Code examples

Basic: submit form, assert success toast

typescript
await aiInput('Order created', '#note');
await aiClick('Submit');
await aiAssertToast('Order created', { type: 'success' });

Regex / partial match (i18n — text varies by locale)

typescript
await aiAssertToast(/Order #\d+ created/, { mode: 'regex' });
await aiAssertToast('created', { mode: 'includes' });

Error path — assert failure toast

typescript
await aiClick('Submit'); // empty form
await aiAssertToast('required', { mode: 'includes', type: 'error' });

Type-only match (text is dynamic)

typescript
await aiAssertToast('', { type: 'error' }); // any error toast

Wait-only, then continue

typescript
await aiClick('Delete');
await aiWaitForToast({ type: 'success' });
await aiClick('Confirm in next dialog');

Multiple / ordering checks via inspect

typescript
await aiClick('Batch import');
await aiWaitForToast({ type: 'success' });
const seen = await aiGetToasts({ sinceLastCall: true });
// assert at least one success and no error
expect(seen.some(t => t.type === 'success')).toBe(true);
expect(seen.every(t => t.type !== 'error')).toBe(true);

Detection rules for type

So the API stays framework-agnostic, type is resolved by convention, not by coupling to any UI lib:

  1. Class heuristic — scan the toast node's class list for keywords: success, error, fail, warning/warn, info, loading. Covers Element (el-message--success), Antd (ant-message-success), most custom libs.
  2. ARIA fallback — role="status" + aria-live → info; role="alert" → error.
  3. Icon fallback — presence of an SVG with class icon-success / icon-error inside the toast.
  4. Default — 'default' if nothing matched.

Rules are ordered 1→4, first match wins; a single regex table drives them so new patterns are one-line additions.

How it composes with existing API

  • Works alongside aiAssert / aiWaitFor — no replacement, purely additive.
  • Only injects the MutationObserver once per page (lazy, on first aiAssertToast/aiWaitForToast/aiGetToasts call), so zero cost when unused.
  • Buffer TTL default 30s (configurable), so a toast that disappeared 5s ago is still assertable — this is exactly what fixes the timing failure.

Attachments

playwright-2026-09-21_10-12-35-1072a500.html