Playwright Clicks and Typing
A person visiting a website rarely just stares at it. That person clicks buttons, types into search boxes, and fills out forms. Clicking and typing are the two most common actions in any Playwright test, forming the building blocks for almost every other interaction.
The Basic Action Pattern
Find the Element (Locator)
|
v
Perform the Action (click or type)
|
v
Page Responds (navigation, message, update)
Clicking an Element
await page.getByRole('button', { name: 'Submit' }).click();This line finds the button labeled "Submit" and clicks it, waiting automatically until the button becomes visible and ready before clicking.
Typing Into a Text Field
await page.getByLabel('Email').fill('user@example.com');The fill method clears any existing text in the field first, then types the new value directly, similar to selecting all text and retyping.
Typing Character by Character
await page.getByLabel('Search').pressSequentially('laptop', { delay: 100 });This method types one character at a time with a small pause between each keystroke, useful for testing search boxes that show live suggestions as a user types.
A Complete Login Example
await page.getByLabel('Username').fill('sarah_connor');
await page.getByLabel('Password').fill('SecurePass123');
await page.getByRole('button', { name: 'Log In' }).click();These three lines mirror the exact steps a real person follows: enter a username, enter a password, click the login button.
Double Clicks and Right Clicks
await page.locator('.file-icon').dblclick();
await page.locator('.menu-item').click({ button: 'right' });A double click often opens a file or enters an editing mode. A right click typically opens a context menu with extra options.
Clicking a Specific Position
await page.locator('#drawing-canvas').click({ position: { x: 50, y: 100 } });Some elements, such as a canvas or map, need a click at an exact pixel position rather than a click anywhere on the element.
Clearing a Field Without Typing
await page.getByLabel('Search').clear();This empties a field completely, useful for resetting a search box before entering a new query in the same test.
Quick Practice Task
Write a short test that opens a search engine, types a query into the search box, and clicks the search button.
Key Takeaways
- Click and fill cover the majority of everyday test actions.
- pressSequentially types character by character for live search behavior.
- Double clicks, right clicks, and position clicks handle special cases.
- These actions form the foundation for every form-based test.
