🎭

Playwright コードスニペット - イベント編

に公開

はじめに

よくあるブラウザ操作について、Playwrightでどのように実装するかをサンプルコードとともに紹介します。

新しいタブを開く

BrowserContext クラスの waitForEvent("page") メソッドを使用します。

import { test, Page } from "@playwright/test";

test("新しいタブを開く", async ({ context, page }) => {
  const newTabPromise: Promise<Page> = context.waitForEvent("page");
  // 新しいタブを開く操作
  await page.getByRole('button', {name: "新しいページ"}).click();
  const newTab: Page = await newTabPromise;
  await newTab.waitForLoadState("domcontentloaded");
  // 新しいタブでの操作

});

ダイアログを開く

Page クラスの waitForEvent("dialog") メソッドを使用します。

import { test } from "@playwright/test";

test("ダイアログを開く", async ({ page }) => {
  // ダイアログを開く操作
  await page.getByRole("button", { name: "ログアウト" }).click();
  page.on("dialog", async (dialog) => {
    await dialog.accept();
  });
  // ログアウトしたことを確認
});

ファイルのダウンロード

Page クラスの waitForEvent("download") メソッドを使用します。

import fs from "fs";
import { Download } from "playwright";
import { test, expect } from "@playwright/test";

test("ファイルのダウンロード", async ({ page }) => {
  const downloadPromise: Promise<Download> = page.waitForEvent("download");
  // ファイルのダウンロード操作
  await page.getByRole("button", { name: "ダウンロード" }).click();
  const download: Download = await downloadPromise;
  const filePath: string = "downloaded.txt";
  await download.saveAs(filePath);
  // ダウンロードしたファイルの存在確認
  expect(fs.existsSync(filePath)).toBeTruthy();
});

ファイルのアップロード

Page クラスの waitForEvent("filechooser") メソッドを使用します。

import fs from "fs";
import { FileChooser } from "playwright";
import { test, expect } from "@playwright/test";

test("ファイルのダウンロード", async ({ page }) => {
  const fileChooserPromise: Promise<FileChooser> = page.waitForEvent("filechooser");
  await page.getByRole("button", { name: "ファイル選択" }).click();
  const fileChooser: FileChooser = await fileChooserPromise;
  const filePath: string = "toUpload.txt";
  await fileChooser.setFiles(filePath);
  await page.getByRole("button", { name: "アップロード" }).click();
  // アップロードが完了したことを確認
});

GitHubで編集を提案

Discussion