0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Last updated at Posted at 2023-09-11

はじめに

よくあるブラウザ操作について、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();
  // アップロードが完了したことを確認
});
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?