🎭
Playwright でファイルをアップロードする方法
環境
- Playwright: 1.38.1
Drag and Drop でファイルをアップロードする
参考情報
drag-and-drop.ts
import { Locator, Page } from "@playwright/test";
import { readFileSync } from "fs";
export const dragAndDrop = async (
page: Page,
locator: Locator,
filePath: string,
fileName: string,
fileType = ""
) => {
const buffer = readFileSync(filePath).toString("base64");
const dataTransfer = await page.evaluateHandle(
async ({ bufferData, localFileName, localFileType }) => {
const dt = new DataTransfer();
const blobData = await fetch(bufferData).then((res) => res.blob());
const file = new File([blobData], localFileName, {
type: localFileType,
});
dt.items.add(file);
return dt;
},
{
bufferData: `data:application/octet-stream;base64,${buffer}`,
localFileName: fileName,
localFileType: fileType,
}
);
await locator.dispatchEvent("drop", { dataTransfer });
};
tests/file-upload.spec.ts
test("Drag and Drop", async ({ page }) => {
await dragAndDrop(
page,
page.getByTestId("dropzone"),
path.join("FILE_PATH", "file_name.pdf"),
"file_name.pdf"
);
});
File Chooser でファイルをアップロードする
参考情報
tests/file-upload.spec.ts
test("File Chooser", async ({ page }) => {
const fileChooserPromise = page.waitForEvent("filechooser");
await page.getByTestId("dropzone-button").click();
const fileChooser = await fileChooserPromise;
await fileChooser.setFiles(path.join("FILE_PATH", "file_name.jpg"));
});
Discussion