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

kcugc4gi  于 2023-05-19  发布在  TypeScript
关注(0)|答案(3)|浏览(372)

我们在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))
);

}

xnifntxz

xnifntxz1#

类似这样的东西应该可以工作(请将其视为伪代码,但我没有时间测试它):

async clickAndWaitForResponses(locator: string, urlsToWaitFor: string[]) {
    const allResponsesPromise = Promise.all(urlsToWaitFor.map(url => page.waitForResponse(url)));
    await this.page.locator(locator).first().click();
    const responses = await allResponsesPromise;
}

// Calling function
await clickAndWaitForResponses(`xpath`, ['url1', url3', 'url2']);
ttvkxqim

ttvkxqim2#

请记住,JavaScript在使用任何循环之前都是async
How to use asyc-await with loops?
一般来说,您可以使用一个方便的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")
      
    ])
dgtucam1

dgtucam13#

所以,我做了大部分的代码,但正在努力解决它。
现在我明白了
这就是答案。

public async _waitForResponse(args: WaitForResponse | Array<WaitForResponse>): Promise<any> {
if (Array.isArray(args)) {
  const responseArray = [];
  for (const arg of args) {
    const response = this._callWaitForResponse(arg);
    responseArray.push(response);
  }
  return Promise.all(responseArray); // This is what i have missed.
} else {
  return this._callWaitForResponse(args);
}

}

相关问题