Actions:
Certainly! Here are some common action commands in Playwright using Java. You'll typically interact with Playwright through its Java bindings, using the Playwright
, Browser
, Page
, and Locator
classes. Below are examples of various actions:
Setup
First, make sure you have the necessary dependencies in your pom.xml
if you're using Maven:
xml<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.33.0</version>
</dependency>
Basic Setup
Here's a basic setup for initializing Playwright in Java:
javaimport com.microsoft.playwright.*;
public class PlaywrightExample {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
Page page = browser.newPage();
page.navigate("https://example.com");
// Add your actions here
browser.close();
}
}
}
Navigation
goto(url): Navigate to a URL.
javapage.navigate("https://example.com");
reload(): Reload the current page.
javapage.reload();
waitForNavigation(): Wait for a navigation to complete.
javapage.waitForNavigation(() -> { page.click("a#link"); });
Interacting with Elements
click(selector): Click an element matching the selector.
javapage.click("button#submit");
dblclick(selector): Double-click an element matching the selector.
javapage.dblclick("button#submit");
fill(selector, text): Fill an input field or textarea with text.
javapage.fill("input#username", "myUsername");
type(selector, text, options): Type text into an input field or textarea.
javapage.type("input#username", "myUsername");
press(selector, key, options): Press a key in an element.
javapage.press("input#username", "Enter");
check(selector): Check a checkbox or radio button.
javapage.check("input#agree");
uncheck(selector): Uncheck a checkbox.
javapage.uncheck("input#agree");
selectOption(selector, values): Select an option from a dropdown.
javapage.selectOption("select#dropdown", "value1");
Waiting for Elements
waitForSelector(selector, options): Wait for an element to appear in the DOM.
javapage.waitForSelector("div#content");
waitForXPath(xpath, options): Wait for an element matching the XPath to appear in the DOM.
javapage.waitForSelector("//div[@id='content']");
Frames
frame(name): Get a frame by its name.
javaFrame frame = page.frame("myFrame");
frameLocator(selector): Get a frame locator.
javaFrameLocator frame = page.frameLocator("iframe[name='myFrame']");
Dialogs
- dialog(handler): Handle dialogs (alerts, confirms, prompts).java
page.onDialog(dialog -> { System.out.println(dialog.message()); dialog.accept(); });
In Playwright, onDialog
and onceDialog
are used to handle dialog events (such as alerts, confirms, prompts, and beforeunloads). They allow you to listen for and interact with these dialogs when they appear. The difference between onDialog
and onceDialog
lies in how they handle the dialog events:
onDialog
:- Purpose: Attaches a persistent listener for all dialog events.
- Usage: Use this when you expect multiple dialog events to occur and you want to handle each one with the same handler.
- Example: Use
onDialog
if a series of actions in your test might trigger multiple dialogs, and you want to handle all of them.
onceDialog
:- Purpose: Attaches a one-time listener that is removed after the first dialog event.
- Usage: Use this when you expect only one dialog event or when you want to handle a specific dialog event and then remove the listener.
- Example: Use
onceDialog
if you know that a specific action will trigger a single dialog, and you want to handle only that one dialog event.
Summary
onDialog
: Use when you expect multiple dialog events and want to handle all of them.onceDialog
: Use when you expect only a single dialog event or want to handle a specific dialog event and then remove the listener.
onDialog
: Use when you expect multiple dialog events and want to handle all of them.onceDialog
: Use when you expect only a single dialog event or want to handle a specific dialog event and then remove the listener.Screenshots and PDFs
screenshot(options): Take a screenshot.
javapage.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png")));
pdf(options): Generate a PDF of the page.
javapage.pdf(new Page.PdfOptions().setPath(Paths.get("page.pdf")));
JavaScript Evaluation
evaluate(pageFunction, args): Evaluate JavaScript in the page context.
javaString title = page.evaluate("() => document.title").toString();
evaluateHandle(pageFunction, args): Evaluate JavaScript and get a handle to a JavaScript object.
javaJSHandle handle = page.evaluateHandle("() => document.body");
Emulating Devices and Viewports
setViewportSize(viewportSize): Set the viewport size.
javapage.setViewportSize(1280, 800);
emulate(options): Emulate a device.
javapage.emulate(new Page.EmulateOptions().setViewport(new ViewportSize(375, 667)).setUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/14A5346a Safari/602.1"));
These are some of the common Playwright action commands in Java. You can combine and use these commands based on your test scenarios.
Introduction
Playwright can interact with HTML Input elements such as text inputs, checkboxes, radio buttons, select options, mouse clicks, type characters, keys and shortcuts as well as upload files and focus elements.
Text input
Using Locator.fill() is the easiest way to fill out the form fields. It focuses the element and triggers an input
event with the entered text. It works.
fill(selector, text)
: This method clears the existing value of the input field and then types the specified text into it. It's useful when you want to replace the entire content of an input field.
for <input>
, <textarea>
and [contenteditable]
elements.
// Text input
page.getByRole(AriaRole.TEXTBOX).fill("Peter");
// Date input
page.getByLabel("Birth date").fill("2020-02-02");
// Time input
page.getByLabel("Appointment time").fill("13-15");
// Local datetime input
page.getByLabel("Local time").fill("2020-03-02T05:15");
Checkboxes and radio buttons
Using Locator.setChecked() is the easiest way to check and uncheck a checkbox or a radio button. This method can be used with input[type=checkbox]
, input[type=radio]
and [role=checkbox]
elements.
// Check the checkbox
page.getByLabel("I agree to the terms above").check();
// Assert the checked state
assertTrue(page.getByLabel("Subscribe to newsletter")).isChecked();
// Select the radio button
page.getByLabel("XL").check();
Select options
Selects one or multiple options in the <select>
element with Locator.selectOption(). You can specify option value
, or label
to select. Multiple options can be selected.
// Single selection matching the value or label
page.getByLabel("Choose a color").selectOption("blue");
// Single selection matching the label
page.getByLabel("Choose a color").selectOption(new SelectOption().setLabel("Blue"));
// Multiple selected items
page.getByLabel("Choose multiple colors").selectOption(new String[] {"red", "green", "blue"});
Mouse click
Performs a simple human click.
// Generic click
page.getByRole(AriaRole.BUTTON).click();
// Double click
page.getByText("Item").dblclick();
// Right click
page.getByText("Item").click(new Locator.ClickOptions().setButton(MouseButton.RIGHT));
// Shift + click
page.getByText("Item").click(new Locator.ClickOptions().setModifiers(Arrays.asList(KeyboardModifier.SHIFT)));
// Ctrl + click or Windows and Linux
// Meta + click on macOS
page.getByText("Item").click(new Locator.ClickOptions().setModifiers(Arrays.asList(KeyboardModifier.CONTROL_OR_META)));
// Hover over element
page.getByText("Item").hover();
// Click the top left corner
page.getByText("Item").click(new Locator.ClickOptions().setPosition(0, 0));
Under the hood, this and other pointer-related methods:
- wait for element with given selector to be in DOM
- wait for it to become displayed, i.e. not empty, no
display:none
, novisibility:hidden
- wait for it to stop moving, for example, until css transition finishes
- scroll the element into view
- wait for it to receive pointer events at the action point, for example, waits until element becomes non-obscured by other elements
- retry if the element is detached during any of the above checks
Forcing the click
Sometimes, apps use non-trivial logic where hovering the element overlays it with another element that intercepts the click. This behavior is indistinguishable from a bug where element gets covered and the click is dispatched elsewhere. If you know this is taking place, you can bypass the actionability checks and force the click:
page.getByRole(AriaRole.BUTTON).click(new Locator.ClickOptions().setForce(true));
Programmatic click
If you are not interested in testing your app under the real conditions and want to simulate the click by any means possible, you can trigger the HTMLElement.click()
behavior via simply dispatching a click event on the element with Locator.dispatchEvent():
page.getByRole(AriaRole.BUTTON).dispatchEvent("click");
Type characters
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.
type(selector, text)
: This method simulates typing the specified text into the input field, character by character. It's useful when you want to simulate a user typing action, preserving any existing content in the input field
Type into the field character by character, as if it was a user with a real keyboard with Locator.pressSequentially().
// Press keys one by one
page.locator("#area").pressSequentially("Hello World!");
This method will emit all the necessary keyboard events, with all the keydown
, keyup
, keypress
events in place. You can even specify the optional delay
between the key presses to simulate real user behavior.
Keys and shortcuts
// Hit Enter
page.getByText("Submit").press("Enter");
// Dispatch Control+Right
page.getByRole(AriaRole.TEXTBOX).press("Control+ArrowRight");
// Press $ sign on keyboard
page.getByRole(AriaRole.TEXTBOX).press("$");
The Locator.press() method focuses the selected element and produces a single keystroke. It accepts the logical key names that are emitted in the keyboardEvent.key property 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 can alternatively specify a single character you'd like to produce such as
"a"
or"#"
. - Following modification shortcuts are also supported:
Shift, Control, Alt, Meta
.
Simple version produces a single character. This character is case-sensitive, so "a"
and "A"
will produce different results.
// <input id=name>
page.locator("#name").press("Shift+A");
// <input id=name>
page.locator("#name").press("Shift+ArrowLeft");
Shortcuts such as "Control+o"
or "Control+Shift+T"
are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.
Note that you still need to specify the capital A
in Shift-A
to produce the capital character. Shift-a
produces a lower-case one as if you had the CapsLock
toggled.
Upload files
You can select input files for upload using the Locator.setInputFiles() method. It expects first argument to point to an input element with the type "file"
. Multiple files can be passed in the array. If some of the file paths are relative, they are resolved relative to the current working directory. Empty array clears the selected files.
// Select one file
page.getByLabel("Upload file").setInputFiles(Paths.get("myfile.pdf"));
// Select multiple files
page.getByLabel("Upload files").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
// Remove all the selected files
page.getByLabel("Upload file").setInputFiles(new Path[0]);
// Upload buffer from memory
page.getByLabel("Upload file").setInputFiles(new FilePayload(
"file.txt", "text/plain", "this is test".getBytes(StandardCharsets.UTF_8)));
If you don't have input element in hand (it is created dynamically), you can handle the Page.onFileChooser(handler) event or use a corresponding waiting method upon your action:
FileChooser fileChooser = page.waitForFileChooser(() -> {
page.getByLabel("Upload file").click();
});
fileChooser.setFiles(Paths.get("myfile.pdf"));
Focus element
For the dynamic pages that handle focus events, you can focus the given element with Locator.focus().
page.getByLabel("Password").focus();
Drag and Drop
You can perform drag&drop operation with 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.
page.locator("#item-to-be-dragged").dragTo(page.locator("#item-to-drop-at"));
Dragging manually
If you want precise control over the drag operation, use lower-level methods like Locator.hover(), Mouse.down(), Mouse.move() and Mouse.up().
page.locator("#item-to-be-dragged").hover();
page.mouse().down();
page.locator("#item-to-drop-at").hover();
page.mouse().up();
If your page relies on the dragover
event being dispatched, you need at least two mouse moves to trigger it in all browsers. To reliably issue the second mouse move, repeat your Mouse.move() or Locator.hover() twice. The sequence of operations would be: hover the drag element, mouse down, hover the drop element, hover the drop element second time, mouse up.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.