To test file uploading with @playwright/test, use the setInputFiles()
method. First, select the input element with the type "file" and pass the file path(s) in an array.
For a single file:
await page.getByLabel('Upload file').setInputFiles('myfile.pdf');
For multiple files:
await page.getByLabel('Upload files').setInputFiles(['file1.txt', 'file2.txt']);
To remove selected files, pass an empty array:
await page.getByLabel('Upload file').setInputFiles([]);
If the input element is created dynamically, handle the page.on('filechooser')
event or use a waiting method:
const fileChooserPromise = page.waitForEvent('filechooser');
await page.getByLabel('Upload file').click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles('myfile.pdf');
You can also upload a buffer from memory:
await page.getByLabel('Upload file').setInputFiles({
name: 'file.txt',
mimeType: 'text/plain',
buffer: Buffer.from('this is test')
});
This offers flexibility when testing various upload scenarios. With these methods, @playwright/test makes it easy to automate file uploading in your tests.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].