如何在 Playwright [typescript] 中等待多个响应

问题描述 投票:0回答:1

我们在 Playwright 中有一个等待响应的方法。

page.waitForResponse

但是,我需要使用 waitForResponse 等待多个响应。我们怎样才能做到这一点?

我试过循环 waitForResponse 方法,但这不起作用。

更新: 我试过的代码:

 async click(locator: string, waitForResponse){
 // waitForResponse = [{url: 'url1'},{url: 'url3'},{url: 'url2'}];
    const [response] = await Promise.all([
            waitForResponse ? this._waitForResponse(waitForResponse) : Promise.resolve(true),
            await this.page.locator(locator).first().click()
          ]);
    }
// Calling function
 await click(`xpath`, [{url: 'url1'},{url: 'url3'},{url: 'url2'}]);

waitForResponse 方法: WaitForResponse 是这里的一个类型。

public async _waitForResponse(args: WaitForResponse | Array<WaitForResponse>): Promise<any> {
if (Array.isArray(args)) {
  const resposneArray = [];
  for (const aa in args) {
    resposneArray.push(await this._callWaitForResponse(args[aa]));
  }
  return resposneArray;
} else {
  return this._callWaitForResponse(args);
}

}

实际的 waitForResponse 方法:

private async _callWaitForResponse(args: WaitForResponse): Promise<any> {
const { requestUrl } = args;
return this.page.waitForResponse((response) =>
  requestUrl.every((url: string) => response.url().includes(url))
);

}

typescript async-await wait playwright playwright-typescript
1个回答
0
投票

请记住,在使用任何循环之前,JavaScript 是

async

如何在循环中使用 asyc-await?


一般来说,您可以使用方便的

custom
函数等待多个响应,如下所示使用Promise.all

async waitForResponseCustom(resName) {
    return await this.page.waitForResponse(async (response) => {
        const body = await response.text();
        return body.includes(resName)
    });
}
    const responses = await Promise.all([
        this.waitForResponseCustom("API 1"),
        this.waitForResponseCustom("API 2")
      
    ])
© www.soinside.com 2019 - 2024. All rights reserved.