Skip to content

Instantly share code, notes, and snippets.

@Tomas2D
Last active July 5, 2022 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tomas2D/b72ee219a4ae69a36dccf80cb7e3eaa1 to your computer and use it in GitHub Desktop.
Save Tomas2D/b72ee219a4ae69a36dccf80cb7e3eaa1 to your computer and use it in GitHub Desktop.
Puppeteer wait for XHR calls
function waitForAjaxCalls(page: Page) {
const task = new Task<void>();
let _expectedCount = Infinity;
let processedCalls = 0;
const handler = (req: HTTPRequest) => {
if (req.method() !== 'POST') {
return;
}
if (req.response().ok()) {
++processedCalls;
} else {
task.reject(new InternalServerErrorException('Failed to load data'));
}
if (processedCalls >= _expectedCount) {
task.resolve();
}
};
page.on('requestfinished', handler);
return (expectedCount: number, timeLimit: number) => {
_expectedCount = expectedCount;
if (processedCalls >= expectedCount) {
task.resolve();
}
const timeoutTask = new Task<void>();
const timeoutId = setTimeout(() => {
timeoutTask.reject(new InternalServerErrorException(`Timeout for data load`));
}, timeLimit);
return Promise.race([task, timeoutTask]).finally(() => {
clearTimeout(timeoutId);
page.off('requestfinished', handler);
});
};
}
// Usage
const callInterceptor = waitForAjaxCalls(page);
const expectedAjaxCallCounts = 10; // image some async action
await monthsAjaxCallInterceptor(expectedAjaxCallCounts, 10 * 1000); // 10 seconds timeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment