File Upload in Playwright
File Upload in Playwright: definition, setInputFiles usage, single and multiple file examples, mistakes, interview notes, and practice.
Definition and Brief Explanation
Definition: File upload in Playwright attaches one or more local files to an input[type="file"] element using setInputFiles.
Explanation: Playwright does not need the operating system file picker. The test directly assigns files to the file input, then verifies that the application accepted the file, showed the file name, preview, validation message, or upload result.
Why It Matters
- It tests a real user requirement: attaching documents, images, resumes, invoices, or evidence files.
- It avoids unreliable operating-system file picker automation.
- It verifies file validation rules such as size, type, required file, and multiple uploads.
- It keeps upload tests fast because the file is assigned directly to the input.
How It Works
- Locate the file input directly or through a visible label.
- Call setInputFiles with one file path or an array of file paths.
- Submit or trigger the upload if the application requires it.
- Assert the uploaded file name, preview, success message, validation error, or backend result.
Syntax and Examples
Example 1: Upload one file
await page.getByLabel('Upload resume').setInputFiles('resume.pdf');
Explanation: Attaches one file to a file input.
Example 2: Upload multiple files
await page.locator('input[type=file]').setInputFiles(['a.png', 'b.png']);
Explanation: Pass an array for multiple files.
Common Mistakes
- Trying to automate the native file picker window.
- Using a file path that does not exist in CI.
- Uploading a file but not asserting the application accepted it.
- Using only input[type=file] when a visible label locator is available.
Interview Notes
- How does Playwright upload a file without using the OS file picker?
- How do you upload multiple files?
- What should you assert after setInputFiles?
- What upload issue commonly fails only in CI?
Practice Task
Create a file upload test for a resume field. Upload one PDF, assert the file name is shown, then try an invalid file type and assert the validation message.