It seems that the way to go is request.respond() indeed, but still, I couldn’t find a concrete example in the web on how to use it. The way I did it was like this:
// Intercept API response and pass mock data for Puppeteer
await page.setRequestInterception(true);
page.on('request', request => {
if (request.url() === constants.API) {
request.respond({
content: 'application/json',
headers: {"Access-Control-Allow-Origin": "*"},
body: JSON.stringify(constants.biddersMock)
});
}
else {
request.continue();
}
});
What happens here exactly?
- Firstly, all requests are intercepted with
page.setRequestInterception() - Then, for each request I look for the one I am interested in, by matching it by URL with
if (request.url() === constants.API)whereconstants.APIis just the endpoint I need to match. - If found, I pass my own response with
request.respond(), otherwise I just let the request continue withrequest.continue()
Two more points:
constants.biddersMockabove is an array- CORS header is important or access to your mock data will not be allowed
Please comment or refer to resources with better example(s).