We have a method in Playwright to wait for a response.
page.waitForResponse
But, I need to wait for multiple responses using waitForResponse. How can we achieve this?
I have tried looping the waitForResponse method, but that doesn't work.
Update: Code I tried:
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 method: WaitForResponse is a type here.
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);
}
}
actual waitForResponse method:
private async _callWaitForResponse(args: WaitForResponse): Promise<any> {
const { requestUrl } = args;
return this.page.waitForResponse((response) =>
requestUrl.every((url: string) => response.url().includes(url))
);
}
Something like this should work (please regard it as pseudo code though, I haven't had time to test it):
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']);