krishworkstech.com

Playwright Actions Illustrated

Playwright Actions Illustrated

Playwright is capable of interacting with HTML input elements, including text inputs, checkboxes, radio buttons, select options, mouse clicks, character typing, key presses, and shortcuts, in addition to uploading files and focusing on elements.

coverimage 2 - part 6

Text input

Utilizing locator.fill() represents the simplest method for populating form fields. This function focuses on the element and initiates an input event with the provided text. It is applicable to <input>, <textarea>, and [contenteditable] elements.

				
					// Text input
await page.getByRole('textbox').fill('Peter');

// Date input
await page.getByLabel('Birth date').fill('2020-02-02');

// Time input
await page.getByLabel('Appointment time').fill('13:15');

// Local datetime input
await page.getByLabel('Local time').fill('2020-03-02T05:15');

				
			

Checkboxes and radio buttons

Utilizing locator.setChecked() represents the simplest method for checking and unchecking a checkbox or a radio button. This function is applicable to input[type=checkbox], input[type=radio], and [role=checkbox] elements.

				
					// Check the checkbox
await page.getByLabel('I agree to the terms above').check();

// Assert the checked state
expect(page.getByLabel('Subscribe to newsletter')).toBeChecked();

// Select the radio button
await page.getByLabel('XL').check();

				
			

Select options

Chooses one or more options within the <select> element using locator.selectOption(). You have the ability to specify either the option value or the label for selection. It is possible to select multiple options.

				
					// Single selection matching the value or label
await page.getByLabel('Choose a color').selectOption('blue');

// Single selection matching the label
await page.getByLabel('Choose a color').selectOption({ label: 'Blue' });

// Multiple selected items
await page.getByLabel('Choose multiple colors').selectOption(['red', 'green', 'blue']);

				
			

Mouse click

Executes a basic human click.

				
					// Generic click
await page.getByRole('button').click();

// Double click
await page.getByText('Item').dblclick();

// Right click
await page.getByText('Item').click({ button: 'right' });

// Shift + click
await page.getByText('Item').click({ modifiers: ['Shift'] });

// Ctrl + click on Windows and Linux
// Meta + click on macOS
await page.getByText('Item').click({ modifiers: ['ControlOrMeta'] });

// Hover over element
await page.getByText('Item').hover();

// Click the top left corner
await page.getByText('Item').click({ position: { x: 0, y: 0 } });

				
			

Beneath the surface, this and other methods related to pointers:

  • await the presence of an element with the specified selector in the DOM
  • await its visibility, meaning it should not be empty, should not have display:none, and should not have visibility:hidden
  • await its stability, for instance, until the CSS transition is complete
  • Scroll the element into the viewport
  • await its ability to receive pointer events at the designated action point, for example, it waits until the element is no longer obscured by other elements
  • Retry again if the element becomes detached during any of the aforementioned checks

Forcing the click

Occasionally, applications implement complex logic in which hovering over an element causes it to be overlaid by another element that captures the click. This behavior can be mistaken for a bug, as the element appears to be obscured and the click is redirected elsewhere. If you are aware that this is occurring, you can circumvent the actionability checks and enforce the click:

				
					await page.getByRole('button').click({ force: true });
				
			

Programmatic click

If you do not wish to test your application in real conditions and prefer to simulate the click using any available method, you can invoke the HTMLElement.click() functionality by merely dispatching a click event on the element using locator.dispatchEvent():

				
					await page.getByRole('button').dispatchEvent('click');
				
			

Type characters

NOTE: Most of the time, you should input text with locator.fill(). See the Text input section above. You only need to type characters if there is special keyboard handling on the page.


Input the characters into the field one by one, as though it were a user utilizing a genuine keyboard with locator.pressSequentially().

				
					// Press keys one by one
await page.locator('#area').pressSequentially('Hello World!');
				
			

Keys and shortcuts

				
					// Hit Enter
await page.getByText('Submit').press('Enter');

// Dispatch Control+Right
await page.getByRole('textbox').press('Control+ArrowRight');

// Press $ sign on keyboard
await page.getByRole('textbox').press('$');

				
			

The locator.press() function targets the chosen element and generates a single keystroke. It takes the logical key names that are provided in the keyboardEvent.key attribute of the keyboard events:

Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape,

ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight,

ArrowUp, F1 – F12, Digit0 – Digit9, KeyA – KeyZ, etc.

  • You may also indicate a specific character that you wish to generate, such as “a” or “#”.
  • The following modification shortcuts are also supported: Shift, Control, Alt, and Meta.

The simplified version generates a single character. This character is sensitive to case, meaning that “a” and “A” will yield different outcomes.

				
					// <input id=name>
await page.locator('#name').press('Shift+A');

// <input id=name>
await page.locator('#name').press('Shift+ArrowLeft');

				
			

Shortcuts like “Control+o” or “Control+Shift+T” are also supported. When used with the modifier, the modifier key must be pressed and held while the next key is pressed.

It is important to remember that you must still specify the capital A in Shift-A to generate the uppercase character. Shift-a will yield a lowercase character, similar to having the CapsLock activated.

Upload files

You have the option to choose input files for upload by utilizing the locator.setInputFiles() method. This method requires the first argument to reference an input element designated with the type “file”. An array can be used to pass multiple files. In cases where some file paths are relative, they will be resolved in relation to the current working directory. An empty array will remove the selected files.

				
					// 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')
});

				
			

If you do not possess the input element (which is generated dynamically), you may manage the page.on(‘filechooser’) event or utilize an appropriate waiting method in response to your action:

				
					// Start waiting for file chooser before clicking. Note no await.
const fileChooserPromise = page.waitForEvent('filechooser');
await page.getByLabel('Upload file').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(path.join(__dirname, 'myfile.pdf'));

				
			

Focus element

For dynamic pages that manage focus events, you can set focus on the specified element using locator.focus().

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

Drag and Drop

You are able to execute a drag and drop operation using locator.dragTo(). This method will:

  • Hover the element that will be dragged.
  • Press left mouse button.
  • Move mouse to the element that will receive the drop.
  • Release left mouse button.
				
					await page.locator('#item-to-be-dragged').dragTo(page.locator('#item-to-drop-at'));

				
			

Dragging manually

For precise control during the drag operation, it is advisable to utilize lower-level methods such as locator.hover(), mouse.down(), mouse.move(), and mouse.up().

				
					await page.locator('#item-to-be-dragged').hover();
await page.mouse.down();
await page.locator('#item-to-drop-at').hover();
await page.mouse.up();

				
			

Note

If your page depends on the dragover event being triggered, it is necessary to have a minimum of two mouse movements to activate it across all browsers. To ensure the second mouse movement is reliably executed, you should repeat your mouse.move() or locator.hover() actions twice. The order of operations would be: hover over the drag element, press the mouse down, hover over the drop element, hover over the drop element a second time, and then release the mouse.

Scrolling

In most cases, Playwright will automatically perform scrolling prior to executing any actions. Consequently, there is no need for you to scroll manually.

				
					// Scrolls automatically so that button is visible
await page.getByRole('button').click();

				
			

Nevertheless, in uncommon situations, it may be necessary to scroll manually. For instance, you may wish to compel an ‘infinite list’ to display additional elements, or adjust the page for a particular screenshot. In these instances, the most dependable method is to identify an element that you wish to bring into view at the bottom and scroll it into visibility.

				
					// Scroll the footer into view, forcing an "infinite list" to load more content
await page.getByText('Footer text').scrollIntoViewIfNeeded();

				
			

If you wish to manage the scrolling with greater precision, consider using mouse.wheel() or locator.evaluate():

				
					// Position the mouse and scroll with the mouse wheel
await page.getByTestId('scrolling-container').hover();
await page.mouse.wheel(0, 10);

// Alternatively, programmatically scroll a specific element
await page.getByTestId('scrolling-container').evaluate(e => e.scrollTop += 100);

				
			

Playwright Essentials: A Step-by-Step Journey into Test Automation

cover - part 9

Part 01: Master Playwright Testing – Framework from Scratch Guide

cover - part 10

Part 02: How to install Playwright

cover - part 11

Part 03: Basic Playwright Test Structure

cover - part 13 (1)

Part 04: Importance of Playwright configuration file and its details to run the tests

cover - part 17

Part 05: Writing Tests in PlayWright

cover - part 19

Part 06: Playwright Actions Illustrated

Scroll to Top
  • Schematic design
  • PCB and schematic source files
  • Assembling drawing files
  • Providing prototype/sample and production PCB service
  • Testing and validation of designed hardware
  • HIPAA
  • Azure Key
  • Management
  • ES, Checksum,
  • MD5sum
  • AWS
  • Azure
  • GCP
  • DigitalOcean
  • Kotlin
  • Python
  • Tensorflow
  • Computer Vision
  • ECG
  • SPO2
  • Heart Rate
  • Glucometer
  • Blood Pressure
  • UX UI Process
  • Figma and FigJam
  • Adobe Suite
  • Selenium Java
  • Postman
  • Swagger
  • Jmeter
  • SQL
  • Java Scripter
  • Test ng
  • Extents Reports
  • Flutter
  • Java
  • Kotlin
  • Swift
  • Dart
  • React JS
  • Python
  • NodeJS
  • Django
  • HTML, CSS, JS
RDBMS
  • PostgreSQL
  • Oracle
  • MySQL
  • MariaDB
No SQL Based
  • MongoDB
  • GCP
  • FirestoreDB
  • DynamoDB
  • Azure
  • CosmosDB
  • AWS