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/locator.md.
close
  • English
  • Locator

    Locator is the core API for querying and interacting with elements in Browser Mode. Build query chains with page.getBy* or page.locator(), then call interaction methods or pass the Locator to expect.element. Execution semantics are determined by the configured browser provider.

    Auto-wait

    With the Playwright provider, Locator action methods (click, fill, check, etc.) wait for the target element to become actionable (visible, enabled, and stable) before running. This differs from the auto-retry behavior of expect.element assertions.

    src/locator.test.ts
    import { page } from '@rstest/browser';
    import { expect, test } from '@rstest/core';
    
    test('interacts with a form using locator', async () => {
      await page.getByLabel('Username').fill('alice');
      await page.getByLabel('Password').fill('secret123');
      await page.getByRole('button', { name: 'Login' }).click();
    
      await expect.element(page.getByLabel('Username')).toHaveValue('alice');
    });

    page

    • Type: BrowserPage

    Entry point for locating elements in a test. Call query methods on page to create a Locator, then chain interactions or pass it to expect.element(...). For focus-based keyboard input, use page.keyboard.

    const submitButton = page.getByRole('button', { name: 'Submit' });
    await submitButton.click();

    BrowserPage

    • Type:
    type BrowserPage = Pick<
      Locator,
      | 'locator'
      | 'getByRole'
      | 'getByText'
      | 'getByLabel'
      | 'getByPlaceholder'
      | 'getByAltText'
      | 'getByTitle'
      | 'getByTestId'
    > & {
      elementLocator: (element: Element) => Locator;
      keyboard: BrowserKeyboard;
      viewport: (width: number, height: number) => Promise<void>;
    };

    Type of page. Provides element queries, DOM-to-Locator conversion, keyboard input, and viewport resizing. Element actions (click, fill, etc.) are methods on Locator.

    page.viewport

    • Type: (width: number, height: number) => Promise<void>

    Resize the current test's layout viewport to check responsive layouts. Both dimensions must be positive integers in CSS pixels. Once await page.viewport(width, height) resolves, media queries and layout reads reflect the new dimensions.

    import { page } from '@rstest/browser';
    import { expect, test } from '@rstest/core';
    
    test('uses the tablet layout', async () => {
      await page.viewport(768, 1024);
      expect(window.matchMedia('(min-width: 768px)').matches).toBe(true);
    });

    Rstest restores the initial viewport after each test execution, including retries (retry) and repeats (repeats). Restoration waits for failure screenshots, afterEach, fixture cleanup, onTestFinished, and onTestFailed callbacks to finish. Tests that do not resize the viewport skip restoration.

    Headless runs restore the browser instance's initial viewport size. Headed runs restore the UI's previous viewport mode. Changes made in afterAll or a cleanup function returned by beforeAll are restored when that group of tests finishes.

    To apply the same size across a group of tests, configure browser.viewport or call page.viewport() in beforeEach. A size set in beforeAll is restored after the first test execution; subsequent retries, repeats, and tests do not keep it.

    Concurrent tests share a viewport, so calling page.viewport() in a concurrent test throws an error. If a group contains concurrent tests that will run, its beforeAll, afterAll, and cleanup functions throw as well.

    In headless mode, Playwright also updates window.screen when resizing the viewport. Restoring the viewport does not reset a screen size configured via browser.providerOptions.context.screen.

    Query API

    All query methods return a Locator and support chaining.

    locator

    • Type: (selector: string, options?: LocatorOptions) => Locator

    Query elements by CSS selector, optionally passing options v1.0.0-beta.1 to filter by descendant Locator or text conditions (has, hasNot, hasText, hasNotText).

    const item = page.locator('.todo-item');
    const activeItem = page.locator('.todo-item', { hasText: 'Active' });

    getByRole

    • Type: (role: LocatorAriaRole | (string & {}), options?: LocatorGetByRoleOptions) => Locator

    Query elements by ARIA role. Prefer this over CSS selectors or test IDs when semantic roles are available.

    const saveBtn = page.getByRole('button', { name: 'Save' });

    getByText

    • Type: (text: string | RegExp, options?: LocatorTextOptions) => Locator

    Query elements by visible text.

    const successMessage = page.getByText('Saved successfully');

    getByLabel

    • Type: (text: string | RegExp, options?: LocatorTextOptions) => Locator

    Query form controls by their label text.

    const emailInput = page.getByLabel('Email');

    getByPlaceholder

    • Type: (text: string | RegExp, options?: LocatorTextOptions) => Locator

    Query inputs by placeholder text.

    const searchInput = page.getByPlaceholder('Search');

    getByAltText

    • Type: (text: string | RegExp, options?: LocatorTextOptions) => Locator

    Query elements by alt text.

    const avatarImage = page.getByAltText('User avatar');

    getByTitle

    • Type: (text: string | RegExp, options?: LocatorTextOptions) => Locator

    Query elements by title attribute.

    const helpIcon = page.getByTitle('Help');

    getByTestId

    • Type: (text: string | RegExp) => Locator

    Query elements by test ID attribute (defaults to data-testid; customize with setTestIdAttribute).

    const settingsPanel = page.getByTestId('settings-panel');

    elementLocator

    • Type: (element: Element) => Locator

    Synchronously wrap a DOM Element from the current test document in a Locator, allowing elements from Testing Library or DOM queries to use browser actions and assertions. HTML and SVG elements, including elements inside shadow DOM, are supported.

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

    The Locator stays bound to the original DOM node without modifying DOM attributes. If a rerender replaces that node, detached assertions pass and actions wait for the original node to reattach or time out; use query Locators such as page.getByRole() when the element should be resolved again after a rerender.

    Elements from other documents or iframes throw an error. Detached elements from the current document can be wrapped before insertion.

    Configuration API

    setTestIdAttribute

    • Type: (attribute: string) => Promise<void>

    Set the attribute name used by getByTestId(). Defaults to 'data-testid'. This forwards to the browser provider (for example, Playwright's selectors.setTestIdAttribute()).

    Because this is a global setting, call it once in a setup file rather than changing it mid-test:

    rstest.setup.ts
    import { setTestIdAttribute } from '@rstest/browser';
    
    await setTestIdAttribute('data-qa');
    rstest.config.ts
    import { defineConfig } from '@rstest/core';
    
    export default defineConfig({
      setupFiles: ['./rstest.setup.ts'],
    });

    Composition API

    filter

    • Type: (options: LocatorFilterOptions) => Locator

    Narrow an existing Locator by text, descendant Locator, or visibility (visible v1.0.0-beta.1) matches.

    const profileSave = page
      .locator('section')
      .filter({ has: page.getByRole('heading', { name: 'Profile' }) })
      .getByRole('button', { name: 'Save' });
    
    const visibleItems = page.locator('li').filter({
      visible: true,
      hasNotText: /archived/i,
      hasNot: page.getByRole('img', { name: 'Locked' }),
    });

    and / or

    • Type: (other: Locator) => Locator

    Combine two Locator conditions (and matches elements satisfying both; or matches elements satisfying either).

    const byRole = page.getByRole('button', { name: 'Submit' });
    const byId = page.locator('#submit');
    
    const exactOne = byRole.and(byId);

    nth / first / last

    • Type:
      • nth(index: number): Locator
      • first(): Locator
      • last(): Locator

    Select a single element by 0-based index, first match, or last match from a Locator matching multiple elements.

    count

    • Type: () => Promise<number>

    Return the number of elements currently matching the Locator. This does not auto-retry; use toHaveCount for assertions.

    const total = await page.getByRole('listitem').count();

    all

    • Type: () => Promise<Locator[]>

    Resolve the current match count and return an array of Locator instances pointing to each matched element via nth(index). This does not auto-wait for elements to appear.

    for (const item of await page.getByRole('listitem').all()) {
      await expect.element(item).toBeVisible();
    }

    Interaction API

    Interaction methods execute browser actions and return Promise<void> (except selectOption, which returns the selected option values).

    Strictness

    Locators are strict. If an action (click, fill, etc.) matches more than one element, it throws an error. Use first(), last(), or nth() to select a single element.

    click

    • Type: (options?: LocatorClickOptions) => Promise<void>

    Click the matched element.

    await page.getByRole('button', { name: 'Submit' }).click();

    dblclick

    • Type: (options?: LocatorDblclickOptions) => Promise<void>

    Double-click the matched element.

    await page.getByText('Open details').dblclick();

    dragTo

    • Type: (target: Locator, options?: LocatorDragToOptions) => Promise<void>

    Drag this element to a target Locator. sourcePosition and targetPosition are coordinates relative to the respective elements' top-left padding-box corners.

    await page.getByTestId('card').dragTo(page.getByTestId('column'));

    hover

    • Type: (options?: LocatorHoverOptions) => Promise<void>

    Hover the pointer over the matched element.

    await page.getByRole('button', { name: 'More' }).hover();

    press

    • Type: (key: string, options?: LocatorPressOptions) => Promise<void>

    Focus the matched element and press a key or key combination (for example, 'Enter' or 'ControlOrMeta+A').

    await page.getByLabel('Search').press('Enter');

    pressSequentially

    • Type: (text: string, options?: LocatorPressOptions) => Promise<void>

    Type text into the element one character at a time, sending key events per character. Use this when the element handles individual key events (such as autocomplete or shortcuts); otherwise prefer fill. delay sets the wait between key presses in milliseconds.

    await page.getByLabel('Search').pressSequentially('rstest');

    fill

    • Type: (value: string, options?: LocatorFillOptions) => Promise<void>

    Set the value of an input, textarea, or contenteditable element.

    await page.getByPlaceholder('Email').fill('[email protected]');

    clear

    • Type: (options?: LocatorClearOptions) => Promise<void>

    Clear the value of an input element. Accepts optional options v1.0.0-beta.1 (force, timeout).

    await page.getByPlaceholder('Email').clear();

    focus

    • Type: (options?: LocatorFocusOptions) => Promise<void>

    Focus the matched element.

    await page.getByLabel('Username').focus();

    blur

    • Type: (options?: LocatorBlurOptions) => Promise<void>

    Remove focus from the matched element.

    await page.getByLabel('Username').blur();

    check

    • Type: (options?: LocatorCheckOptions) => Promise<void>

    Check a checkbox or radio button.

    await page.getByLabel('Agree').check();

    uncheck

    • Type: (options?: LocatorCheckOptions) => Promise<void>

    Uncheck a checkbox.

    await page.getByLabel('Agree').uncheck();

    scrollIntoViewIfNeeded

    • Type: (options?: LocatorScrollIntoViewIfNeededOptions) => Promise<void>

    Scroll the page if needed so the matched element is in the viewport.

    await page.getByRole('button', { name: 'Load more' }).scrollIntoViewIfNeeded();

    waitFor

    • Type: (options?: LocatorWaitForOptions) => Promise<void>

    Wait until the matched element reaches the specified state ('attached', 'detached', 'visible', or 'hidden').

    await page.getByText('Ready').waitFor();

    dispatchEvent

    • Type: (type: string, eventInit?: LocatorDispatchEventInit, options?: LocatorDispatchEventOptions) => Promise<void>

    Dispatch a DOM event on the matched element. type must be a non-empty string, eventInit must be JSON-serializable (BrowserSerializable), and options v1.0.0-beta.1 accepts { timeout? }.

    await page.getByRole('button', { name: 'Event' }).dispatchEvent('custom');

    selectOption

    • Type: (values: LocatorSelectOptionValue, options?: LocatorSelectOptionOptions) => Promise<string[]>

    Select option(s) on a <select> element by value string, or v1.0.0-beta.1 { value?, label?, index? }, an array of those values, or null to clear selections. Resolves with the array of selected option values v1.0.0-beta.1.

    await page.getByLabel('Choice').selectOption('b');
    await page.getByLabel('Choice').selectOption({ label: 'Option B' });

    setInputFiles

    • Type: (files: string | string[], options?: LocatorSetInputFilesOptions) => Promise<void>

    Set file path(s) on an <input type="file"> element. Only string or string[] file paths are supported.

    await page.locator('#upload').setInputFiles('/tmp/demo.txt');

    Option and helper types

    All option and helper types below are exported from @rstest/browser:

    type LocatorAriaRole =
      | 'alert'
      | 'alertdialog'
      | 'button'
      | 'checkbox'
      | 'dialog'
      | 'heading'
      | 'link'
      | 'listitem'
      | 'textbox'
      | /* ...standard WAI-ARIA roles */;
    
    type LocatorTextOptions = {
      exact?: boolean;
    };
    
    type LocatorGetByRoleOptions = {
      name?: string | RegExp;
      exact?: boolean;
      checked?: boolean;
      disabled?: boolean;
      expanded?: boolean;
      selected?: boolean;
      pressed?: boolean;
      includeHidden?: boolean;
      level?: number;
    };
    
    type LocatorFilterOptions = {
      hasText?: string | RegExp;
      hasNotText?: string | RegExp;
      has?: Locator;
      hasNot?: Locator;
      visible?: boolean;
    };
    
    type LocatorOptions = Omit<LocatorFilterOptions, 'visible'>;
    
    type LocatorKeyboardModifier =
      'Alt' | 'Control' | 'ControlOrMeta' | 'Meta' | 'Shift';
    
    type LocatorMouseButton = 'left' | 'right' | 'middle';
    
    type LocatorPosition = {
      x: number;
      y: number;
    };
    
    type LocatorClickOptions = {
      button?: LocatorMouseButton;
      clickCount?: number;
      delay?: number;
      force?: boolean;
      modifiers?: LocatorKeyboardModifier[];
      position?: LocatorPosition;
      timeout?: number;
      trial?: boolean;
    };
    
    type LocatorDblclickOptions = Omit<LocatorClickOptions, 'clickCount'>;
    
    type LocatorHoverOptions = Pick<
      LocatorClickOptions,
      'force' | 'modifiers' | 'position' | 'timeout' | 'trial'
    >;
    
    type LocatorDragToOptions = {
      force?: boolean;
      sourcePosition?: LocatorPosition;
      targetPosition?: LocatorPosition;
      timeout?: number;
      trial?: boolean;
    };
    
    type LocatorPressOptions = {
      delay?: number;
      timeout?: number;
    };
    
    type LocatorFillOptions = {
      force?: boolean;
      timeout?: number;
    };
    
    type LocatorClearOptions = {
      force?: boolean;
      timeout?: number;
    };
    
    type LocatorCheckOptions = {
      force?: boolean;
      position?: LocatorPosition;
      timeout?: number;
      trial?: boolean;
    };
    
    type LocatorFocusOptions = {
      timeout?: number;
    };
    
    type LocatorBlurOptions = {
      timeout?: number;
    };
    
    type LocatorScrollIntoViewIfNeededOptions = {
      timeout?: number;
    };
    
    type LocatorWaitForOptions = {
      state?: 'attached' | 'detached' | 'visible' | 'hidden';
      timeout?: number;
    };
    
    type BrowserSerializable =
      | null
      | boolean
      | number
      | string
      | BrowserSerializable[]
      | { [key: string]: BrowserSerializable };
    
    type LocatorDispatchEventInit = BrowserSerializable;
    
    type LocatorDispatchEventOptions = {
      timeout?: number;
    };
    
    type LocatorSelectOptionItem = {
      value?: string;
      label?: string;
      index?: number;
    };
    
    type LocatorSelectOptionValue =
      | null
      | string
      | LocatorSelectOptionItem
      | readonly string[]
      | readonly LocatorSelectOptionItem[];
    
    type LocatorSelectOptionOptions = {
      force?: boolean;
      timeout?: number;
    };
    
    type LocatorSetInputFilesOptions = {
      timeout?: number;
    };

    Usage constraints

    • Only the methods documented on this page are currently supported from the Playwright Locator API.
    • Arguments to and(), or(), dragTo(), locator(_, { has | hasNot }), and filter({ has | hasNot }) must be Locator instances returned by @rstest/browser.
    • dispatchEvent(type, eventInit?, options?) requires a non-empty type string and a JSON-serializable eventInit.
    • selectOption() only accepts null, string, { value?, label?, index? }, string[], or an array of { value?, label?, index? } (mixed string/object arrays and DOM elements are not supported). setInputFiles() only accepts string or string[] file paths.

    Using with expect.element

    Pass any Locator to expect.element(locator) for auto-retrying assertions. See Assertion.