Wait strategies in run-code
Playwright provides several wait strategies: `await page.waitForLoadState('networkidle')` waits for network idle state; `await page.locator(...).waitFor({ state: 'hidden' })` waits for an element to reach a specific state; `await page.waitForFunction(() => ...)` waits for a function to return true; `await page.locator(...).waitFor({ timeout: <ms> })` waits with a custom timeout.
Locators auto-wait and retry without explicit waitFor
Playwright locators always auto-wait and retry when needed, so explicit waitFor or waitForElementToBeRemoved calls are typically not required. When you cannot find a suitable assertion, use expect.poll() instead for custom waiting logic.
Playwright fill action replaces Testing Library type
Testing Library's await user.type(screen.getByLabelText('Password'), 'secret') is replaced with await component.getByLabel('Password').fill('secret') in Playwright.
Playwright click action for user events
Testing Library's await user.click(screen.getByText('Click me')) is replaced with await component.getByText('Click me').click() in Playwright. For async waiters, both await user.click(await screen.findByText('Click me')) and await component.getByText('Click me').click() produce the same result since Playwright locators auto-wait.
Playwright tests perform actions and assert state
Playwright tests are designed around two core concepts: performing actions on elements and asserting the state against expectations. There is no need to manually wait for anything prior to performing an action, as Playwright automatically waits for actionability checks to pass. Similarly, there is no need to deal with race conditions when performing checks, as Playwright assertions are designed to describe expectations that need to be eventually met. This design allows developers to avoid flaky timeouts and racy checks.
Playwright automatically waits for actionability checks before actions
Playwright automatically waits for the wide range of actionability checks to pass prior to performing each action. Developers do not need to explicitly wait for elements to become actionable.
Basic Playwright locator actions for C#
The most common Playwright locator actions are: Locator.check (check an input checkbox), Locator.click (click the element), Locator.uncheck (uncheck an input checkbox), Locator.hover (hover mouse over the element), Locator.fill (fill a form field, input text), Locator.focus (focus the element), Locator.press (press a single key), Locator.setInputFiles (pick files to upload), and Locator.selectOption (select option in a drop down).
Page.GotoAsync waits for page load state
When using Page.GotoAsync to navigate to a URL in C#, Playwright waits for the page to reach the load state prior to moving forward.
Locator.blur calls blur on element
The method Locator.blur() calls blur on the element, equivalent to HTMLElement.blur().
Locator.check ensures checkbox or radio is checked
The method Locator.check() ensures that a checkbox or radio element is checked. It performs these steps: (1) Ensures element is a checkbox or radio input, throws if not; if already checked, returns immediately; (2) Waits for actionability checks unless force option is set; (3) Scrolls element into view if needed; (4) Uses Page.mouse to click center of element; (5) Ensures element is now checked, throws if not. If element detaches during action, throws. Throws TimeoutError if not finished within timeout.
Locator.clear clears input field
The method Locator.clear() clears an input field. It waits for actionability checks, focuses the element, clears it and triggers an input event after clearing. Throws if target element is not an input, textarea, or contenteditable element. However, if the element is inside a label element that has an associated control, the control will be cleared instead.
Locator.click action steps
The method Locator.click() clicks an element by performing these steps: (1) Waits for actionability checks unless force option is set; (2) Scrolls element into view if needed; (3) Uses Page.mouse to click center of element or specified position; (4) Waits for initiated navigations to succeed or fail unless noWaitAfter option is set. If element detaches during action, throws. Throws TimeoutError if not finished within timeout.
Locator.dblclick double clicks element
The method Locator.dblclick() double clicks an element by performing these steps: (1) Waits for actionability checks unless force option is set; (2) Scrolls element into view if needed; (3) Uses Page.mouse to double click center of element or specified position. If element detaches during action, throws. Throws TimeoutError if not finished within timeout. The dblclick() method dispatches two click events and a single dblclick event.
Locator.dispatchEvent programmatically dispatches event
The method Locator.dispatchEvent(type, eventInit) programmatically dispatches an event on the matching element. The type parameter is the DOM event type (e.g., 'click', 'dragstart'). The eventInit parameter is optional and event-specific initialization properties. The method creates an event instance based on the type, initializes it with eventInit properties, and dispatches it on the element. Events are composed, cancelable and bubble by default.
Locator.dragTo drags element to target
The method Locator.dragTo(target) drags the locator to another target locator or target position. It first moves to the source element, performs a mousedown, then moves to the target element or position and performs a mouseup. You can specify exact positions relative to the top-left corners of elements using sourcePosition and targetPosition options.
Locator.drop simulates drag-and-drop of files or data
The method Locator.drop(payload) simulates an external drag-and-drop of files or clipboard-like data onto the locator. It dispatches native dragenter, dragover, and drop events at the center of the target element with a synthetic DataTransfer carrying the provided files and/or data entries. Works cross-browser. If the target element's dragover listener does not call preventDefault(), the target is considered to have rejected the drop and the method throws.
Locator.fill sets input field value
The method Locator.fill(value) sets a value to an input field. It waits for actionability checks, focuses the element, fills it and triggers an input event after filling. You can pass an empty string to clear the input field. Throws if target element is not an input, textarea, or contenteditable element. However, if element is inside a label with an associated control, the control will be filled instead. To send fine-grained keyboard events, use Locator.pressSequentially().
Locator.focus calls focus on element
The method Locator.focus() calls focus on the matching element, equivalent to HTMLElement.focus().
Locator.hover hovers over element
The method Locator.hover() hovers over the matching element by performing these steps: (1) Waits for actionability checks unless force option is set; (2) Scrolls element into view if needed; (3) Uses Page.mouse to hover over center of element or specified position. If element detaches during action, throws. Throws TimeoutError if not finished within timeout.
Locator.press() focuses and presses keys
The press() method focuses the matching element and presses a combination of keys. It supports key values like F1-F12, Digit0-Digit9, KeyA-KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, etc. Modification shortcuts supported include Shift, Control, Alt, Meta, ShiftLeft, ControlOrMeta. ControlOrMeta resolves to Control on Windows and Linux and to Meta on macOS. Shortcuts like 'Control+o', 'Control++', or 'Control+Shift+T' are supported. The delay option specifies time in milliseconds between keydown and keyup, defaulting to 0.
Locator.pressSequentially() types characters one by one
The pressSequentially() method focuses the element and sends a keydown, keypress/input, and keyup event for each character in the text. It is useful for simulating user typing behavior. The delay option specifies time in milliseconds to wait between key presses, defaulting to 0. Example: await locator.pressSequentially('Hello') types instantly, while await locator.pressSequentially('World', { delay: 100 }) types slower like a user.
Locator.screenshot() captures element screenshot
The screenshot() method takes a screenshot of the element matching the locator. It waits for actionability checks, then scrolls the element into view before taking a screenshot. If the element is covered by other elements, it will not be visible on the screenshot. If the element is a scrollable container, only currently scrolled content will be visible. Returns a buffer with the captured screenshot. The method throws an error if the element is detached from DOM.
Locator.scrollIntoViewIfNeeded() scrolls element if needed
The scrollIntoViewIfNeeded() method waits for actionability checks, then tries to scroll the element into view unless it is completely visible as defined by IntersectionObserver's ratio.
Locator.selectOption() selects option in select element
The selectOption() method selects option or options in a <select> element. It waits for actionability checks and waits until all specified options are present in the <select> element before selecting them. Returns an array of option values that have been successfully selected. Triggers change and input events once all options have been selected. If the target element is not a <select>, this method throws an error. However, if the element is inside a <label> element that has an associated control, the control will be used instead.
Locator.selectText() selects all text in element
The selectText() method waits for actionability checks, then focuses the element and selects all its text content. If the element is inside a <label> element that has an associated control, it focuses and selects text in the control instead.
Locator.setChecked() sets checkbox or radio state
The setChecked() method sets the state of a checkbox or a radio element. It performs the following steps: 1) Ensure that matched element is a checkbox or a radio input, throwing if not. 2) If the element already has the right checked state, return immediately. 3) Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried. 4) Scroll the element into view if needed. 5) Use Page.mouse to click in the center of the element. 6) Ensure that the element is now checked or unchecked, throwing if not.
Locator.setInputFiles() uploads files to input type=file
The setInputFiles() method uploads file or multiple files into <input type=file>. For inputs with a [webkitdirectory] attribute, only a single directory path is supported. Relative paths are resolved relative to the current working directory. For empty array, clears the selected files. The method expects Locator to point to an input element. However, if the element is inside a <label> element that has an associated control, targets the control instead. Supports uploading single files, multiple files, directories, removing all selected files, and uploading buffer from memory with name, mimeType, and buffer properties.
Locator.tap() performs tap gesture on element
The tap() method performs a tap gesture on the element matching the locator. It performs the following steps: 1) Wait for actionability checks on the element, unless force option is set. 2) Scroll the element into view if needed. 3) Use Page.touchscreen to tap the center of the element, or the specified position. If the element is detached from the DOM at any moment during the action, this method throws. Requires that the hasTouch option of the browser context be set to true.
Locator.textContent() returns node.textContent
The textContent() method returns the node.textContent of the element. When asserting text on the page, it is recommended to use LocatorAssertions.toHaveText() instead to avoid flakiness.
Locator.type() is deprecated in favor of fill() or pressSequentially()
The type() method is deprecated. In most cases, you should use Locator.fill() instead. You only need to press keys one by one if there is special keyboard handling on the page, in which case use Locator.pressSequentially(). The type() method focuses the element and sends a keydown, keypress/input, and keyup event for each character in the text.
Locator.uncheck() ensures checkbox or radio is unchecked
The uncheck() method ensures that checkbox or radio element is unchecked. It performs the following steps: 1) Ensure that element is a checkbox or a radio input, throwing if not. If the element is already unchecked, return immediately. 2) Wait for actionability checks on the element, unless force option is set. 3) Scroll the element into view if needed. 4) Use Page.mouse to click in the center of the element. 5) Ensure that the element is now unchecked, throwing if not. If the element is detached from the DOM at any moment during the action, this method throws.
Locator.waitFor() waits for element to satisfy state condition
The waitFor() method returns when element specified by locator satisfies the state option. If target element already satisfies the condition, the method returns immediately. Otherwise, waits for up to the specified timeout in milliseconds until the condition is met.
Locator.waitForFunction() waits for custom element condition
The waitForFunction() method returns when the provided expression returns a truthy value, called with the matching element as a first argument and optional arg as a second argument. This is a generic way to wait for an element to reach a custom condition without asserting it. The locator is re-resolved on each retry, so it tolerates the element being re-rendered while waiting. If the expression returns a Promise, this method will wait for the promise to resolve before checking its value. If the expression throws or rejects, this method throws.
File upload using setInputFiles() example
Example showing how to handle file uploads with Playwright using setInputFiles():
```js
// Select one file
await page.getByLabel('Upload file').setInputFiles(path.join(__dirname, 'myfile.pdf'));
// Select multiple files
await page.getByLabel('Upload files').setInputFiles([
path.join(__dirname, 'file1.txt'),
path.join(__dirname, 'file2.txt'),
]);
// Select a directory
await page.getByLabel('Upload directory').setInputFiles(path.join(__dirname, 'mydir'));
// Remove all the selected files
await page.getByLabel('Upload file').setInputFiles([]);
// Upload buffer from memory
await page.getByLabel('Upload file').setInputFiles({
name: 'file.txt',
mimeType: 'text/plain',
buffer: Buffer.from('this is test')
});
```
pressSequentially() example for password field
Example showing how to use pressSequentially() with a password field:
```js
const locator = page.getByLabel('Password');
await locator.pressSequentially('my password');
await locator.press('Enter');
```
selectOption() example for select element
Example showing how to use selectOption() with different selection methods:
```js
// single selection matching the value or label
element.selectOption('blue');
// single selection matching the label
element.selectOption({ label: 'Blue' });
// multiple selection for red, green and blue options
element.selectOption(['red', 'green', 'blue']);
```
waitForFunction() example waiting for attribute
Example showing how to use waitForFunction() to wait for an attribute to appear:
```js
const toggle = page.getByRole('button', { name: 'Menu' });
await toggle.click();
await toggle.waitForFunction(element => element.hasAttribute('aria-expanded'));
```
waitForFunction() example with argument
Example showing how to pass an argument to waitForFunction():
```js
await page.getByTestId('status').waitForFunction((element, value) => {
return element.textContent === value;
}, 'Ready');
```