หลักการ Upload ไฟล์ใน Playwright

Playwright ไม่ใช้การคลิกปุ่ม Upload แล้วเลือกไฟล์ แบบมนุษย์ แต่จะอัปโหลดไฟล์โดยตรงผ่าน <input type="file">

คีย์หลักคือคำสั่ง

setInputFiles()

1. Upload Single File

HTML ตัวอย่าง

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

Playwright

await page.setInputFiles('#upload', 'tests/files/example.png');

อธิบาย

  • #upload → selector ของ <input type="file">
  • 'tests/files/example.png' → path ของไฟล์ (relative / absolute ก็ได้)
  • Playwright จะใส่ไฟล์เข้า input ทันที เหมือนผู้ใช้เลือกไฟล์

ใช้ได้กับ:

  • ปุ่ม Upload
  • Drag & Drop (ถ้ามี <input type="file"> ซ่อนอยู่)

2. Upload Multiple Files

HTML ตัวอย่าง

<input type="file" id="upload" multiple>

Playwright

await page.setInputFiles('#upload', [
  'tests/files/file1.pdf',
  'tests/files/file2.jpg',
  'tests/files/file3.png'
]);

อธิบาย

  • ส่งเป็น array
  • <input> ต้องมี multiple
  • เหมาะกับอัปโหลดหลายไฟล์พร้อมกัน

3. Upload โดยใช้ locator (แนะนำ)

Playwright แนะนำให้ใช้ locator

const uploadInput = page.locator('input[type="file"]');

await uploadInput.setInputFiles('tests/files/example.png');

หรือหลายไฟล์

await uploadInput.setInputFiles([
  'tests/files/file1.pdf',
  'tests/files/file2.jpg'
]);

✅ โค้ดอ่านง่าย ✅ ทนต่อการเปลี่ยน DOM มากกว่า

4. Upload + ตรวจสอบว่าไฟล์ถูกเลือกแล้ว

const input = page.locator('#upload');

await input.setInputFiles('tests/files/example.png');

// ตรวจสอบชื่อไฟล์
await expect(input).toHaveValue(/example\.png/);

💡 ใช้ regex เพราะ browser อาจใส่ path ปลอม (C:\fakepath\...)

5. Upload ไฟล์จาก Buffer / สร้างไฟล์เอง

เหมาะกับ Test ที่ไม่อยากเก็บไฟล์จริง

await page.setInputFiles('#upload', {
  name: 'hello.txt',
  mimeType: 'text/plain',
  buffer: Buffer.from('Hello Playwright!')
});

📌 ใช้ได้ทั้ง single & multiple

6. Clear / Remove File (ยกเลิกการเลือกไฟล์)

await page.setInputFiles('#upload', []);

เหมือนผู้ใช้กดลบไฟล์ออก

7. ตัวอย่าง Test แบบครบ ๆ

test('upload single file', async ({ page }) => {
  await page.goto('https://example.com/upload');

  await page.setInputFiles(
    'input[type="file"]',
    'tests/files/example.png'
  );

  await page.click('button[type="submit"]');

  await expect(page.locator('.success')).toHaveText('Upload success');
});

❌ สิ่งที่ "ไม่ควรทำ"

  • ไม่ต้องใช้ page.click() แล้วเลือกไฟล์
  • ไม่ต้องใช้ keyboard.type() ใส่ path
  • ไม่ต้องใช้ Robot / AutoIT

Playwright จัดการให้หมดแล้ว 👍