Purpose
- When performing website testing, validating file upload functionality is crucial as users need to upload documents and images, such as in job portals, eCommerce websites, cloud storage systems, and others.
- Automating this process ensures reliability and efficiency in testing these functionalities, and automated testing tools like Playwright provide effective solutions for this task. In this blog, we delve into how to handle file upload in Playwright, exploring techniques to handle file upload and automate file upload functionality.
Playwright – File Upload
- 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
Playwright Method to File Upload
// Select one file
page.locator("(//input[@type='file'])[1]").setInputFiles(Paths.get("myfile.pdf"));
// Select multiple files
page.locator("(//input[@type='file'])[1]").setInputFiles(new Path[] {Paths.get("file1.txt"), Paths.get("file2.txt")});
Example ::
package com.example;
import com.microsoft.playwright.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class FileUpload {
public static void main(String[] args) {
Playwright playwright = Playwright.create() ;
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
.setHeadless(false));
Page page = browser.newPage();
//example1 "
// String url = "https://ps.uci.edu/~franklin/doc/file_upload.html";
// page.navigate(url);
// page.setInputFiles("input[name='userfile']", Paths.get("C:\\Users\\Nageswar\\Desktop\\TestPlan\\TestFileUpload.txt"));
// Example 2
String url1 = "https://www.west-wind.com/wconnect/wcscripts/fileupload.wwd";
page.navigate(url1);
// page.setInputFiles("(//input[@type='file'])[1]", Paths.get("C:\\Users\\Nageswar\\Desktop\\TestPlan\\TestFileUpload.txt"));
page.locator("(//input[@type='file'])[1]")
.setInputFiles(new Path[] { Paths.get("C:\\Users\\Nageswar\\Desktop\\TestPlan\\TestFileUpload.txt"),
Paths.get("C:\\Users\\Nageswar\\Desktop\\PFT\\Consolidate Result_01.xlsx")});
}
}
Comments
Post a Comment