wfmn17
wfmn17

Reputation: 204

How to log all requests with Playwright

I use playwright's request: APIRequestContext fixture to implement API tests, and I'd like to log all request/responses, but I cannot figure out how. In case of Page fixture, I can monitor the network traffic and log them, but the Request fixture does not provide anything similar.

I use an extended playwright/test and override / add additional fixtures, based on: https://playwright.dev/docs/test-fixtures#overriding-fixtures

Any ideas for a top level solution to log all traffic made view Request fixture?

Upvotes: 6

Views: 5423

Answers (2)

vl4d1m1r4
vl4d1m1r4

Reputation: 1781

I had the same problem, wanted to log all request data before making put or post request and make it visible in the HTML report as well. What I did was defined a proxy to log needed data for the post and put requests:

const globalTest = test.extend<ProjectProps>({
  request: async ({ request }, use) => {
    const requestProxy = new Proxy<APIRequestContext>(request, {
      get(target, prop: keyof APIRequestContext) {
        if (typeof prop === 'string' && ['post', 'put'].includes(prop)) {
          return async (url: string, options: Record<string, unknown>) => {
            const payload = options?.data || null;
            globalTest.step(`Request method: ${prop}, Payload: ${JSON.stringify(payload)}`, () => {});
            return await target[prop](url, options);
          };
        }
        return target[prop];
      },
    });

    await use(requestProxy);
  },
});

I used an empty test.step to make the payload visible in the HTML report, you can replace it with whatever logic for logging you have. Also for the responses you can store the response in a variable from the call instead of returning it like in my case and log it as well.

One change you will see in the report is that all steps for the request context methods will be with proxy.{method} instead of apiRequestContext.{method}, but it was not a problem for me.

Upvotes: 0

ANISH SAJI  KUMAR
ANISH SAJI KUMAR

Reputation: 130

You can use request.on('response') event to log the response:

const request = context.request({
  url: 'https://example.com',
  method: 'GET',
});

request.on('response', (response) =&gt; {
  console.log(response.status());
  console.log(response.headers());
  console.log(response.body());
});

await request.send();

Upvotes: -2

Related Questions