how to log request object in playwright API testing

63 views Asked by At

I am using Playwright for API testing and to log request object in Playwright using the code below. I tried a few options but none of them worked. Can someone suggest how to do that? Thanks!

 test("create new stuff", async ({request}) => {
  const newIssue = await request.post(`http://xyz/account/00000/test`, {
    data: {
      name: "test 123",
      parentTagId: "60b2b3ce-fa32-4b65-8f71-83e9efc75638",
      type: 1
    }
  });
// await console.log(request); // not working
// await console.log(request['data']); //not working
  expect(request).toEqual(201);
  expect(newIssue.status()).toEqual(201);
  expect(newIssue.body()).toContainEqual(expect.objectContaining({
    title: '[Bug] report 1',
    body: 'Bug description'
  }));
});
2

There are 2 answers

0
unickq On

You can't access data in your cases because request is instance of APIRequestContext, not an actual request object.

import { expect, test } from "@playwright/test";

test("create new stuff", async ({ request }) => {
  const payload = {
    name: "paul rudd",
    movies: ["I Love You Man", "Role Models"],
  };

  //   const form = {
  //     title: "Book Title",
  //     author: "John Doe",
  //   };
  //   const multipart = {
  //     fileField: fs.createReadStream("data.csv"),
  //   };

  const response = await request.post(`https://reqres.in/api/users`, {
    data: payload,
    // form,
    // multipart,
  });

  expect(await response.json()).toMatchObject(
    expect.objectContaining({
      name: payload.name,
    }),
  );
});

The second argument of request.post(url, options) is just an object where you add your payload. Just generate your payload before the test and validate it after