0

How to intercept multiple http requests (API calls) with jest & puppeteer environment? I have the following code but I get error Request already handled when I make more than one API call.

Code:

    export const apiPostMethodResponseStatusCheckUtil = async (
    apiObject: APIObject) => {                                                     
     let completeAPIURL = URLs.apiURL + apiObject.endpoint;                                       
     describe(apiObject.testDescribe, () => {
     let expectedResponse = 200;

    it(apiObject.testCaseMsg, async () => {
      console.log("API Request: " + completeAPIURL);
      console.log("API Payload: " + JSON.stringify(apiObject.apiPayload));
      await page.setRequestInterception(true);

      page.on("request", (interceptedRequest) => {
        var data = {
          method: "POST",
          postData: JSON.stringify(apiObject.apiPayload),
        };
        interceptedRequest.continue(data);
      });

      await page.goto(completeAPIURL, {
        waitUntil: "load",
        timeout: apiObject.responseTimeout,
      });

      page.on("response", async (response) => {
        if (response.url().includes(apiObject.includesInURL)) {
          console.log("API response status...." + response.status());
          expect(response.status()).toBe(expectedResponse);
        }
      });
    });
  });
};

How to disable request interception after each API call?

let apiBody1=new APIObject(page, "{entity}/getFirstSet", "getFirstSet", {"_from":0,"_size":200,"_sort":{"id":"asc"}}, 0, `set 1`, `Making API call for set 1 `);
// call util method
apiPostMethodResponseStatusCheckUtil(apiBody1)

let apiBody2=new APIObject(page, "{entity}/getSecondSet", "getSecondSet", {"_from":0,"_size":200,"_sort":{"name":"asc"}}, 0, `set 2`, `Making API call for set 2`);
    // call util method
    apiPostMethodResponseStatusCheckUtil(apiBody2)
user923499
  • 305
  • 1
  • 6
  • 18
  • Where is `page` defined? It looks as though you might be calling `page.setRequestInterception` and creating `request` event callbacks multiple times on the same `page` (for each call to `apiPostMethodResponseStatusCheckUtil`). This could be part of the problem. – Alan Friedman Jun 01 '22 at 10:32
  • @AlanFriedman So, is it not possible to create request event callbacks multiple times on same page by disabling or aborting the request interception after each request? – user923499 Jun 01 '22 at 11:40
  • @AlanFriedman Just to give an overview, I need to make several API requests in the same page, is it possible? – user923499 Jun 01 '22 at 12:10
  • Typically, you would set up a single request event callback and handle all API requests using that callback function. For instance, you could move `page.on("request", (interceptedRequest) => {...}` into a `beforeAll` so it's only created once. – Alan Friedman Jun 01 '22 at 13:14

0 Answers0