Skip to content

Instantly share code, notes, and snippets.

@teyamagu
Last active March 7, 2024 04:36
Show Gist options
  • Save teyamagu/e706fbb2e9a53d25cbf797845935a28a to your computer and use it in GitHub Desktop.
Save teyamagu/e706fbb2e9a53d25cbf797845935a28a to your computer and use it in GitHub Desktop.
waitForNetworkIdleInTargetDomain (Original Idea by souchan2000)
import { chromium, test, expect, Page } from '@playwright/test';
test('テスターちゃんのサイトが表示されるか', async() => {
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
const page = await browser.newPage();
await page.goto('https://testerchan.hatenadiary.com/');
await page.screenshot({ path: `images/test.png` });
await waitForNetworkIdleInTargetDomain(page, "facebook.com");
const title = await page.title();
await console.log(title);
expect(title).toBe('テスターちゃん【4コマ漫画】');
await page.waitForTimeout(5000);
await browser.close();
});
const waitForNetworkIdleInTargetDomain = async (page: Page, targetDomain: string) => {
const devTools = await page.context().newCDPSession(page);
await devTools.send('Network.enable');
let counter = 0;
devTools.on('Network.responseReceived', (responseReceived) => {
if (responseReceived.response.url.includes(targetDomain)) counter = counter + 1;
});
for (;;) {
// イベント発生を待つ
await page.waitForTimeout(500);
// 0.5秒間に指定ドメインへの通信のレスポンスがなかったら待ちを解除する
console.log(`${targetDomain} responses: ${counter}`);
if (counter === 0) break;
counter = 0;
}
await devTools.send('Network.disable');
};
@souchan2000
Copy link

Gistありがとうございます!
responseが来たらcounterの値を増やしてるんですかね?
見た感じだと通信中はcounterが0になるのでそのまますり抜けるんじゃないかなと思いました

ちなみに、requestオブジェクトの配列を用意しておいて、

  • requestWillBeSentイベントが発生したらrequestオブジェクトを配列に格納
  • responseReceived等のイベントが発生したら、そのrequestのidを元に配列からfindしたものを削除する

みたいな作りにするとタイムアウトしたときに何のrequestが残ってるか追いやすいのでおすすめです

よかったら参考くださいー、指摘違ってたらすみません!

@teyamagu
Copy link
Author

teyamagu commented Mar 7, 2024

ありがとうございます!そうですね。
ただ、このメソッドってそもそもRequest発行させる何某かの処理の後に呼ばれることが多そうで、 requestWillBeSentresponseReceived の数のズレをどうするかなぁ、なんて悩んでます

@souchan2000
Copy link

souchan2000 commented Mar 7, 2024

specの始めに devTools.on('Network.responseReceived' ~ を書いておくのはどうでしょう、context fixtureをoverrideするでも良いかも。
https://playwright.dev/docs/test-fixtures#overriding-fixtures

@teyamagu
Copy link
Author

teyamagu commented Mar 7, 2024

やはり、その解になりますか。リクエスト出してレスポンスなくテストがFailすることとか考えると、requestオブジェクト保持しつづけるの微妙かなぁと思っていたのですが、なんとかなるかな。

ありがとうございます!やってみまーす

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment