To interact with input fields in @playwright/test, you can use the following methods:
locator.fill()
This method focuses on the element and triggers an input event with the entered text. It works for <input>
, <textarea>
, and [contenteditable]
elements.
import { test, expect } from '@playwright/test';
test('Fill input field', async ({ page }) => {
await page.goto('https://ray.run/');
const inputLocator = page.locator('input[name="email"]');
await inputLocator.fill('[email protected]');
expect(await inputLocator.inputValue()).toBe('[email protected]');
});
locator.clear()
This method focuses on the element, clears it, and triggers an input event after clearing. If the target element is not an <input>
, <textarea>
, or [contenteditable]
element, this method throws an error.
import { test, expect } from '@playwright/test';
test('Clear input field', async ({ page }) => {
await page.goto('https://ray.run/');
const inputLocator = page.locator('input[name="email"]');
await inputLocator.fill('[email protected]');
await inputLocator.clear();
expect(await inputLocator.inputValue()).toBe('');
});
locator.type()
This method types characters into a field character by character, emitting all necessary keyboard events such as keydown, keyup, and keypress events. You can specify optional delays between key presses to simulate real user behavior.
import { test, expect } from '@playwright/test';
test('Type into input field', async ({ page }) => {
await page.goto('https://ray.run/');
const inputLocator = page.locator('input[name="email"]');
await inputLocator.type('[email protected]', { delay: 100 });
expect(await inputLocator.inputValue()).toBe('[email protected]');
});
locator.press()
This method focuses on the selected element and produces a single keystroke based on logical key names emitted in keyboardEvent.key property of keyboard events like Backquote, Minus, etc. Modification shortcuts such as Shift, Control, Alt, and Meta are also supported.
import { test, expect } from '@playwright/test';
test('Press key in input field', async ({ page }) => {
await page.goto('https://ray.run/');
const inputLocator = page.locator('input[name="email"]');
await inputLocator.type('[email protected]');
await inputLocator.press('Enter');
// Continue with the test after pressing Enter
});
These methods should cover most common scenarios for interacting with input fields in your @playwright/test scripts.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].