File Upload in Playwright

In Playwright, file upload refers to the process of automating the action of selecting and submitting files through an HTML file input element (<input type="file">). Normally, in a web application, when a user wants to upload a file, they click the "Choose File" button, and the system’s file picker dialog opens. However, automation tools like Playwright cannot interact with the operating system’s file picker directly because it is outside the browser’s scope.

Instead, Playwright handles file uploads by directly setting the file path(s) to the <input type="file"> element in the DOM. This way, the need to interact with the native dialog is bypassed.

In Playwright Java, uploading a file is done using the setInputFiles() method. This method is used with an <input type="file"> element to simulate file uploads, just like a user would select a file using a file chooser dialog.


Key Points in Theory:

  • File Input Element: The automation must target an element of type file. Uploading only works with this type of input field since browsers restrict file access for security reasons.
  • Bypassing File Picker Dialog: Playwright avoids interacting with the native dialog window. Instead, it programmatically attaches the specified file to the input element.
  • Single or Multiple Files: If the file input supports multiple files (multiple attribute), Playwright can upload more than one file at once.
  • Security Model: Browsers prevent arbitrary file uploads by requiring automation tools to specify exact file paths on the machine. Playwright complies with this security model and only uploads what is explicitly provided.
  • Clearing Files: Just like a user can remove an already chosen file, Playwright can also clear the selected files from the input if needed.
  • Form Submission: After setting the file on the input, the automation can proceed with form submission or trigger any JavaScript events tied to file selection.



Steps to Upload a File in Playwright (Java)

  • Locate the file input element on the page using a suitable locator.
  • Use setInputFiles(Path file) or setInputFiles(FilePayload file) to simulate uploading the file.
  • Optionally, click the submit button if needed.

URL: https://the-internet.herokuapp.com/upload













Example Scenario

Let's assume we have an HTML element like:

<input type="file" id="uploadFile">


Java Code Example

import com.microsoft.playwright.*;
import java.nio.file.Paths;

public class FileUploadExample {
    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();

            // Go to a page with file upload field
            page.navigate("https://the-internet.herokuapp.com/upload");

            // Locate the input element and upload file
            page.locator("input#file-upload").setInputFiles(Paths.get("example.txt"));

            // Click the Upload button
            page.locator("input#file-submit").click();

            // Optional: verify upload success message
            String uploadedMessage = page.locator("h3").textContent();
            System.out.println("Upload Result: " + uploadedMessage);
        }
    }
}


Explanation of above code:

(a) page.navigate() will navigate to the webpage
(b) locate to the web element and set the input file to be uploaded
(c) Click on the upload button
(d) file become uploaded and print the uploaded message on console








Maven Dependency 


<dependency>
  <groupId>com.microsoft.playwright</groupId>
  <artifactId>playwright</artifactId>
  <version>1.43.0</version> <!-- Use latest version -->
</dependency>


Playwright with Junit

  

In Playwright for Javaassertions are used to verify conditions during automated browser testing—such as checking whether a particular element is visible, enabled, contains the right text, etc.

Playwright for Java uses JUnit or TestNG for assertions. You can also use Playwright’s Assertions class directly (available in the com.microsoft.playwright.assertions package).


How Playwright and JUnit Work Together

  • JUnit provides the test structure, while Playwright handles browser automation.
  • Each test method in JUnit can represent a scenario, such as logging into a website, filling a form, or verifying UI behavior.
  • Playwright is integrated inside these test methods to launch browsers, navigate pages, and perform actions.

Benefits of Using Playwright with JUnit

(a) Organized Test Execution: JUnit makes it easy to group tests, run them together, and get structured reports.

(b) Assertions and Validations: JUnit provides built-in assertion methods to validate Playwright’s actions and outputs.

(c) Lifecycle Management: JUnit has @Before and @After style annotations to manage setup (e.g., starting Playwright/browser) and cleanup (closing browser).

(d) Parallel Execution: Both JUnit and Playwright support running tests in parallel, which helps speed up automation suites.

(e) Integration with CI/CD: JUnit results (in XML/HTML format) are easily integrated with tools like Jenkins, GitHub Actions, or Maven for continuous testing.













Common Assertion Types in Playwright Java

Here are some common assertions:


Assertion TypeMethod in Java
Element is visibleAssertions.assertThat(locator).isVisible();
Element has textAssertions.assertThat(locator).hasText("value");
Element is enabledAssertions.assertThat(locator).isEnabled();
Element is hiddenAssertions.assertThat(locator).isHidden();
Element contains valueAssertions.assertThat(locator).hasValue("value");
Title is correctpage.title() and assert using Assertions or JUnit



Example: Assert on a Login Page
















import com.microsoft.playwright.*;
import com.microsoft.playwright.assertions.PlaywrightAssertions;
import org.junit.jupiter.api.*;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

public class LoginTest {
    static Playwright playwright;
    static Browser browser;
    static Page page;
    static BrowserContext context;

    @BeforeAll
    static void setup() {
        playwright = Playwright.create();
        browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
        context = browser.newContext();
        page = context.newPage();
    }

    @Test
    void testLoginPageAssertions() {
        // Navigate to login page
        page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

        // Assertion: Page title should contain "OrangeHRM"
        String title = page.title();
        Assertions.assertTrue(title.contains("OrangeHRM"), "Page title does not match");

        // Assertion: Check if username input field is visible
        Locator usernameField = page.locator("input[name='username']");
        assertThat(usernameField).isVisible();

        // Assertion: Check if login button is enabled
        Locator loginButton = page.locator("button[type='submit']");
        assertThat(loginButton).isEnabled();

        // Assertion: Check placeholder in username field
        Assertions.assertEquals("Username", usernameField.getAttribute("placeholder"));
    }

    @AfterAll
    static void tearDown() {
        context.close();
        browser.close();
        playwright.close();
    }
}


Code explanation:


SectionPurpose
Playwright.create()Initializes Playwright engine.
browser.newContext()Creates a fresh browser context (like incognito).
page.navigate()Opens the specified login URL.
LocatorIdentifies elements like input fields and buttons.
assertThat(locator).Playwright’s built-in assertions (visibility, text, etc.).
Assertions.assertEquals or assertTrueJUnit assertions for values like title, attributes.