Mastering Query Parameters in Playwright API Tests

HOME

https://jsonplaceholder.typicode.com/comments?users=2

npm install playwright

import { defineConfig } from '@playwright/test';

export default defineConfig({
  reporter: 'html',
});

// Define a type for the expected structure of a comment
type Comment = {
  postId: number;
  id: number;
  name: string;
  email: string;
  body: string;
};

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

test('API Testing - Query Params with Playwright', async ({ request }) => {
  const queryParams = new URLSearchParams({ postId: '1' });

  // Perform a GET request
  const response = await request.get(`https://jsonplaceholder.typicode.com/comments?${queryParams.toString()}`);

  // Check the response status code
  expect(response.status()).toBe(200);

  // Parse the response data
  const responseBody = await response.json();
  console.log(responseBody);

  // Assertions based on expected response
  const postIds = responseBody.map((item: Comment) => item.postId);
  console.log(postIds);

  // Assert that every postId in the response is '1'
  expect([...new Set(postIds)]).toEqual([1]);

  // Extract IDs from the response body
  const ids = responseBody.map((item: Comment) => item.id);
  console.log(ids);

  // Expected IDs to assert against
  const expectedIds = [1, 2, 3, 4, 5];

  // Assert that the IDs are as expected
  expect(ids).toEqual(expectedIds);
});
type Comment = {
  postId: number;
  id: number;
  name: string;
  email: string;
  body: string;
};
import { test, expect } from '@playwright/test';
test('API Testing - Query Params with Playwright', async ({ request })
const queryParams = new URLSearchParams({ postId: '1' });
const response = await request.get(`https://jsonplaceholder.typicode.com/comments?${queryParams.toString()}`);
 expect(response.status()).toBe(200);
const responseBody = await response.json();
console.log(responseBody);
// Assertions based on expected response
  const postIds = responseBody.map((item: Comment) => item.postId);
  console.log(postIds);

  // Assert that every postId in the response is '1'
  expect([...new Set(postIds)]).toEqual([1]);

  // Extract IDs from the response body
  const ids = responseBody.map((item: Comment) => item.id);
  console.log(ids);

  // Expected IDs to assert against
  const expectedIds = [1, 2, 3, 4, 5];

  // Assert that the IDs are as expected
  expect(ids).toEqual(expectedIds);

npx playwright test api_queryparam_tests.spec.ts

npx playwright show-report

Leave a comment