0
0

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】待機処理の逆引きメモ

0
Posted at

はじめに

待機処理で個人的によく使うものを逆引きメモでまとめました。
気になった点など随時更新予定です。

環境

  • @playwright/test@1.54.1

Playwright公式の待機についてのページメモ

要素が完全に表示されるまで待機する

await page.waitForSelector(`${selector}`, { state: 'visible' });

optionsの指定で非表示になるまで待機も可能

await page.waitForSelector(`${selector}`, { state: 'hidden' });

options.stateのデフォルトは「visible」。

  • attached: 要素がDOMに存在するのを待つ。
  • detached: 要素がDOMに存在しないことを待つ。
  • visible:要素のバウンディングボックスが空ではなく、visibility:hiddenでないことを待つ。display:noneの要素などは空のバウンディングボックスを持つためvisibleにならないので注意。
  • hidden:要素がDOMから切り離されるか、空のバウンディングボックスを持つか、visibility:hiddenになるのを待つ。visibleと逆。

参考:Page | Playwright

処理がTrueを返すまで待機する

例)要素が1件以上になるまで待機する

await page.waitForFunction(() => {
    const count = document.querySelectorAll(
        '.sample-element'
    ).length;
    return count > 1;
});

参考:waitForFunction | Playwright

特定のページに遷移するまで待機する

await page.getByRole("button", { name: "トップへ戻る" }).click();  // 'https://sample.com/top'に遷移するボタンを押下
await page.waitForURL('https://sample.com/top'); // 'https://sample.com/top'に遷移するまで待機する

URLの部分一致でも待機可能

以下、https://sample.com/Event/Detail?id=1234-abcd-5678-efghに遷移するまで待機するサンプル

sample.spec.ts
await page.waitForURL("**/Event/Detail?id=*"); 
sample.spec.ts
await page.waitForURL((url) => url.toString().includes(baseUrl('/Event/Detail')));

参考:Page | Playwright

APIリクエストのレスポンスを受け取るまで待機する

すべてのRequestResponseを監視できる。
page.waitForResponse()を使用することで待機できる。
APIリクエスト前に下記を記述する。

const responsePromise = page.waitForResponse('**/sample_api/fetch_data');

// リクエストURLに該当文字列を含む
const postResPromise = await page.waitForResponse(
                async (response) =>
                    response.request().method() === "POST" &&
                    response.url().includes(`sample_api/v1/events/${対象ID}`)
            );
const apiResponse = await postResPromise;

ステータスやレスポンス内容の確認が可能。

例:ステータス201が返っているか

await expect(apiResponse.status()).toBe(201);

例:APIが返すレスポンスサンプル

sample.json
{
	result: {
		id: "xxxx-xxxx-xxxx"
	}
}

上記レスポンスからidを取得する。

sample.spec.ts
let resBody = await apiResponse.json();
 console.log(resBody.result?.id); // 'xxxx-xxxx-xxxx'

参考:Network | Playwright

指定した時間待機する

基本は使用しない。

待機する理由に合わせて、前述の待機処理を使用する。
どうしても解決しない場合やテスト作成時の仮の待機処理として使用する。

await page.waitForTimeout(1000);
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?