For AI agents: the complete documentation index is available at https://rstest.rs/llms.txt, the full documentation bundle is available at https://rstest.rs/llms-full.txt, and this page is available as Markdown at https://rstest.rs/api/runtime-api/browser-mode/assertion.md.
close
  • English
  • Assertion

    expect.element creates auto-retrying DOM assertions for a Locator or DOM Element in Browser Mode. Importing @rstest/browser in a Browser Mode test extends @rstest/core's expect with expect.element() and expect(target).toMatchScreenshot().

    src/assertion.test.ts
    import { page } from '@rstest/browser';
    import { expect, test } from '@rstest/core';
    
    test('asserts element states in browser mode', async () => {
      await expect
        .element(page.getByRole('button', { name: 'Save' }))
        .toBeVisible();
    
      await expect.element(page.getByLabel('Agree')).toBeUnchecked();
      await page.getByLabel('Agree').check();
      await expect.element(page.getByLabel('Agree')).toBeChecked();
    
      await expect
        .element(page.getByRole('button', { name: 'Save' }))
        .toHaveAttribute('id', 'save-btn');
    });

    expect.element

    • Type: (target: Locator | Element) => BrowserElementExpect

    BrowserElementExpect exposes .not and all element matchers documented below.

    Auto-retry and timeout

    With the Playwright provider, expect.element matchers are web-first assertions: they retry until the condition holds or the timeout expires, so manual waitFor or polling loops are unnecessary.

    // Uses the Browser Mode expect.poll.timeout default (5000ms),
    // capped by the remaining time of the current test
    await expect.element(page.getByText('Done')).toBeVisible();
    
    // Override with a longer timeout
    await expect.element(page.getByText('Done')).toBeVisible({ timeout: 10000 });

    Timeout priority

    1. Per-assertion timeout: options.timeout passed directly to the matcher has the highest priority, including 0. With Playwright, an explicit 0 removes the matcher deadline when there is no finite active test or hook deadline; inside a finite non-concurrent test or hook, it is still capped by the remaining scope timeout.
    2. Configured poll timeout: When no matcher timeout is passed, assertions use expect.poll.timeout (1000ms in Node Mode, 5000ms in Browser Mode).
    3. Remaining test or hook timeout: Outside concurrent flows, the effective timeout is capped by the active test or hook deadline (15000ms by default for Browser Mode tests). Without a per-assertion override, it is min(expect.poll.timeout, remainingTime); with an explicit matcher timeout, it is min(timeout, remainingTime).

    For test.concurrent, use the test-scoped expect fixture (async ({ expect }) => ...) so assertions respect that test's remaining deadline. The shared file-level expect uses expect.poll.timeout because browsers cannot reliably track concurrent async flows. Hooks inside describe.concurrent follow the same rule, though they can still be ended by the enclosing hook timeout.

    Failure output

    When an assertion times out, the error reports the expected state, actual state, and timeout:

    Error: Expected element to be visible
      Locator: getByText('Loading complete')
      Timeout: 5000ms

    Input constraints

    • target must be an Rstest Locator or a DOM Element from the current test document. Hand-crafted objects and locators from other libraries throw an error.
    • expect.element is only available in Browser Mode; Node tests use standard expect(value) assertions.

    DOM elements

    expect.element() also accepts DOM elements returned by Testing Library or native DOM queries. It converts the element via page.elementLocator() and uses the same retry and timeout rules as Locator assertions.

    import { getByRole } from '@testing-library/dom';
    
    const button = getByRole(document.body, 'button', { name: 'Save' });
    await expect.element(button).toBeEnabled();
    await expect.element(button).not.toBeDisabled();

    Retries keep checking that same DOM node. If a rerender replaces it, use a query Locator to resolve the replacement. Elements from another document or iframe are rejected.

    Screenshot matching

    toMatchScreenshot

    • Type:
    function toMatchScreenshot(options?: ToMatchScreenshotOptions): Promise<void>;
    function toMatchScreenshot(
      name?: string,
      options?: ToMatchScreenshotOptions,
    ): Promise<void>;

    With the Playwright provider, captures a Locator or page screenshot and compares it against a stored PNG reference. The first run saves a reference when snapshot updates allow new snapshots; subsequent runs compare against it, and --update replaces mismatched references. .not is not supported.

    By default, the current test name identifies the reference. Pass name to share a reference across assertions or distinguish multiple screenshots in one test, or pass only an options object to keep the default reference name. Unnamed assertions in the same test are numbered starting at 1. In test.concurrent, use the test-scoped expect fixture (async ({ expect }) => ...) to use the test name, or pass name explicitly when using the shared file-level expect.

    await expect(page.getByRole('button', { name: 'Save' })).toMatchScreenshot(
      'primary-save-button',
    );
    
    await expect(page.locator('#profile-card')).toMatchScreenshot({
      maxDiffPixels: 20,
      stabilityTimeout: 1000,
      mask: [page.locator('[data-testid="updated-at"]')],
    });

    When a reference exists, a regular assertion passes as soon as the first capture matches it within the configured tolerance. If the first capture differs, Rstest waits until two consecutive captures have the same dimensions and match within that tolerance before comparing against the reference again. Creating or updating a reference also uses the stability check.

    ToMatchScreenshotOptions options (exported from @rstest/browser v1.0.0-beta.2):

    OptionDefaultBehavior
    threshold0.1Per-pixel color distance threshold from 0 (strict) to 1 (loose).
    maxDiffPixelsundefinedMaximum number of differing pixels allowed. Can be combined with maxDiffPixelRatio (the stricter limit applies).
    maxDiffPixelRatioundefinedMaximum fraction of differing pixels allowed (0 to 1). Can be combined with maxDiffPixels (the stricter limit applies).
    stabilityTimeout5000Maximum time in ms to wait for consecutive captures to match. Set to 0 to disable; positive values must be at least 100.
    maskundefinedLocator[] of dynamic areas to cover during capture.
    maskColor'#FF00FF'Fill color for masked areas.
    fullPagefalseCapture the full scrollable page instead of the viewport. Only supported on page assertions.
    styleundefinedAdditional CSS string injected before capture.
    caret'hide'Whether to hide ('hide') or keep ('initial') the text caret during capture.
    scale'device'Screenshot scale ('css' or 'device').
    omitBackgroundfalseOmit the default white page background so transparent areas stay transparent.

    With neither maxDiffPixels nor maxDiffPixelRatio set, no pixels may differ after applying threshold. Rstest disables CSS animations during capture. Reference PNGs are stored under __screenshots__ grouped by test file, with the sanitized reference name, browser, and OS in the filename (plus a stable hash suffix if sanitization could collide). On mismatch, Rstest writes the actual screenshot and diff image to a sibling __failures__ directory. Capture uses the remaining active test timeout; with testTimeout: 0, stabilityTimeout still applies.

    Set project-wide matcher defaults and reference paths with browser.expect.toMatchScreenshot.

    Element screenshots

    Pass a Locator to capture only the matched element:

    await expect(page.getByRole('button', { name: 'Save' })).toMatchScreenshot();

    Page screenshots

    Pass page from @rstest/browser to capture the current viewport, or set fullPage: true for the full page:

    await expect(page).toMatchScreenshot();
    await expect(page).toMatchScreenshot('full-page', { fullPage: true });

    Element assertions

    Only the matchers listed below are currently supported. All matchers accept an optional options?: { timeout?: number } parameter unless stated otherwise.

    not

    • Type: BrowserElementExpect

    Negates the chained matcher.

    await expect
      .element(page.getByRole('button', { name: 'Submit' }))
      .not.toBeDisabled();

    toBeVisible

    • Type: (options?: { timeout?: number; visible?: boolean }) => Promise<void>

    Asserts that the element is mounted and visible (non-empty bounding box and visibility !== 'hidden'). display: none and zero-size elements fail; opacity: 0 still counts as visible. Pass { visible: false } v1.0.0-beta.1 to assert that the element is hidden.

    await expect.element(page.getByRole('button', { name: 'Save' })).toBeVisible();

    toBeHidden

    • Type: (options?: { timeout?: number }) => Promise<void>

    Asserts that the Locator matches no DOM node or matches a non-visible node (the inverse of toBeVisible).

    await expect.element(page.getByTestId('loading')).toBeHidden();

    toBeEnabled

    • Type: (options?: { timeout?: number; enabled?: boolean }) => Promise<void>

    Asserts that the element is not disabled (neither disabled, inside a disabled fieldset, nor aria-disabled="true"). Pass { enabled: false } v1.0.0-beta.1 to assert that the element is disabled.

    await expect
      .element(page.getByRole('button', { name: 'Submit' }))
      .toBeEnabled();

    toBeDisabled

    • Type: (options?: { timeout?: number }) => Promise<void>

    Asserts that the element is disabled (inverse of toBeEnabled).

    await expect
      .element(page.getByRole('button', { name: 'Submit' }))
      .toBeDisabled();

    toBeChecked

    • Type: (options?: { timeout?: number; checked?: boolean; indeterminate?: boolean }) => Promise<void>

    Asserts that a checkbox or radio control has checked === true. Pass { checked: false } or { indeterminate: true } v1.0.0-beta.1 to assert an unchecked or indeterminate checkbox state.

    await expect.element(page.getByLabel('Agree')).toBeChecked();
    await expect
      .element(page.getByLabel('Select all'))
      .toBeChecked({ indeterminate: true });

    toBeUnchecked

    • Type: (options?: { timeout?: number }) => Promise<void>

    Asserts that a checkbox or radio control has checked === false.

    await expect.element(page.getByLabel('Agree')).toBeUnchecked();

    toBeAttached

    • Type: (options?: { timeout?: number; attached?: boolean }) => Promise<void>

    Asserts that the node is connected to a Document or ShadowRoot (Node.isConnected === true), regardless of visibility. Pass { attached: false } v1.0.0-beta.1 to assert that the element is detached.

    await expect.element(page.locator('#toast')).toBeAttached();

    toBeDetached

    • Type: (options?: { timeout?: number }) => Promise<void>

    Asserts that the Locator no longer resolves to a connected DOM node.

    await expect.element(page.locator('#toast')).toBeDetached();

    toBeEditable

    • Type: (options?: { timeout?: number; editable?: boolean }) => Promise<void>

    Asserts that the element is both enabled and not read-only (readonly or aria-readonly="true"). Pass { editable: false } v1.0.0-beta.1 to assert that the element is read-only.

    await expect.element(page.getByLabel('Bio')).toBeEditable();

    toBeFocused

    • Type: (options?: { timeout?: number }) => Promise<void>

    Asserts that the element is the active focus target in the document.

    await expect.element(page.getByLabel('Username')).toBeFocused();

    toBeEmpty

    • Type: (options?: { timeout?: number }) => Promise<void>

    Asserts that an editable element's value is empty or a regular element has no text content.

    await expect.element(page.locator('#empty-state')).toBeEmpty();

    toBeInViewport

    • Type: (options?: { timeout?: number; ratio?: number }) => Promise<void>

    Asserts that the element intersects the viewport based on Intersection Observer semantics. ratio sets the minimum intersection ratio (for example, 0.5 requires at least half the element to be visible).

    await expect.element(page.locator('#hero')).toBeInViewport({ ratio: 0.5 });

    toHaveRole

    • Type: (role: LocatorAriaRole | (string & {}), options?: { timeout?: number }) => Promise<void>

    Asserts the element's exact ARIA role (role inheritance is not matched).

    await expect.element(page.getByTestId('save')).toHaveRole('button');

    toHaveAccessibleName

    • Type: (name: string | RegExp, options?: { timeout?: number; ignoreCase?: boolean }) => Promise<void>

    Asserts the element's accessible name. Strings match the full normalized name. Set ignoreCase: true v1.0.0-beta.1 for case-insensitive matching.

    await expect.element(page.getByTestId('save')).toHaveAccessibleName('Save');

    toHaveAccessibleDescription

    • Type: (description: string | RegExp, options?: { timeout?: number; ignoreCase?: boolean }) => Promise<void>

    Asserts the element's accessible description. Strings match the full normalized description. Set ignoreCase: true v1.0.0-beta.1 for case-insensitive matching.

    await expect
      .element(page.getByTestId('save'))
      .toHaveAccessibleDescription('Saves your changes');

    toHaveText

    • Type: (text: string | RegExp | readonly (string | RegExp)[], options?: { timeout?: number; ignoreCase?: boolean; useInnerText?: boolean }) => Promise<void>

    Asserts that the element's text content (including descendants, with whitespace normalized) matches text. Pass an array v1.0.0-beta.1 to assert the exact text list of all matched elements in order. Set useInnerText: true v1.0.0-beta.1 to compare element.innerText instead of element.textContent, and ignoreCase: true v1.0.0-beta.1 for case-insensitive matching.

    await expect.element(page.getByRole('status')).toHaveText('Saved');
    await expect
      .element(page.getByRole('listitem'))
      .toHaveText(['First', 'Second']);

    toContainText

    • Type: (text: string | RegExp | readonly (string | RegExp)[], options?: { timeout?: number; ignoreCase?: boolean; useInnerText?: boolean }) => Promise<void>

    Asserts that the element's text content (with whitespace normalized) contains the string substring or matches the RegExp. Pass an array v1.0.0-beta.1 to assert that each matched element contains the corresponding entry. Supports ignoreCase and useInnerText v1.0.0-beta.1.

    await expect.element(page.getByRole('status')).toContainText('Save');

    toHaveValue

    • Type: (value: string | RegExp, options?: { timeout?: number }) => Promise<void>

    Asserts that a form control (input, textarea, select) has a value matching value.

    await expect.element(page.getByLabel('Email')).toHaveValue('[email protected]');

    toHaveValues

    • Type: (values: (string | RegExp)[], options?: { timeout?: number }) => Promise<void>

    Asserts all selected option values of a <select multiple> element in DOM order. Pass [] to assert that no options are selected.

    const languages = page.getByLabel('Languages');
    await languages.selectOption(['typescript', 'rust']);
    await expect.element(languages).toHaveValues(['typescript', /^rust$/]);

    toHaveId

    • Type: (value: string | RegExp, options?: { timeout?: number }) => Promise<void>

    Asserts that the element's id matches value.

    await expect
      .element(page.getByRole('button', { name: 'Save' }))
      .toHaveId('save-btn');

    toHaveClass

    • Type: (value: string | RegExp | readonly (string | RegExp)[], options?: { timeout?: number }) => Promise<void>

    Asserts that the element's class attribute matches value. Strings match the entire class string; pass an array v1.0.0-beta.1 to match multiple elements, or use toContainClass to match individual class names.

    await expect.element(page.getByRole('alert')).toHaveClass(/error/);

    toContainClass

    • Type: (value: string | readonly string[], options?: { timeout?: number }) => Promise<void>

    Asserts that the element's classList contains the expected class name(s) (space-separated strings match every listed class). Pass a string array to assert across multiple matched elements in order. Regular expressions are not supported.

    await expect.element(page.getByRole('alert')).toContainClass('error');
    await expect
      .element(page.getByRole('listitem'))
      .toContainClass(['item', 'item active']);

    toHaveAttribute

    • Type:
    function toHaveAttribute(
      name: string,
      options?: { timeout?: number },
    ): Promise<void>;
    function toHaveAttribute(
      name: string,
      value?: string | RegExp,
      options?: { timeout?: number; ignoreCase?: boolean },
    ): Promise<void>;

    Asserts that attribute name exists when value is omitted (or undefined)—including the two-argument toHaveAttribute(name, options) overload v1.0.0-beta.1—or that its value matches when value is provided. Set ignoreCase: true v1.0.0-beta.1 for case-insensitive value matching.

    await expect
      .element(page.getByRole('button', { name: 'Save' }))
      .toHaveAttribute('type', { timeout: 1000 });
    await expect
      .element(page.getByRole('button', { name: 'Save' }))
      .toHaveAttribute('type', 'submit', { ignoreCase: true });

    toHaveCount

    • Type: (count: number, options?: { timeout?: number }) => Promise<void>

    Asserts that the Locator resolves to exactly count elements.

    await expect.element(page.getByRole('listitem')).toHaveCount(3);

    toHaveCSS

    • Type: (name: string, value: string | RegExp, options?: { timeout?: number }) => Promise<void>

    Asserts that the computed CSS property name (non-empty string) matches value.

    await expect.element(page.getByRole('alert')).toHaveCSS('display', 'block');

    toHaveJSProperty

    • Type: (name: string, value: unknown, options?: { timeout?: number }) => Promise<void>

    Asserts that the DOM element's JavaScript property name (non-empty string) equals value (value must be JSON-serializable).

    await expect
      .element(page.getByLabel('Agree'))
      .toHaveJSProperty('checked', true);