Last active
July 5, 2022 15:05
-
-
Save Tomas2D/b72ee219a4ae69a36dccf80cb7e3eaa1 to your computer and use it in GitHub Desktop.
Puppeteer wait for XHR calls
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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