Send JSON File as Payload in Playwright

HOME

npm install playwright

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

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

import { test, expect } from '@playwright/test';
const fs = require('fs');

test('Send JSON file as payload', async ({ request }) => {

  try {
    // Read and parse JSON file directly into a JavaScript object
    const jsonPayload = JSON.parse(fs.readFileSync('tests/payloads/jsonpayload.json', 'utf8'));

    console.log('JSON data parsed successfully:', jsonPayload);

    // Perform a POST request
    const postResponse = await request.post('https://jsonplaceholder.typicode.com/users', {
      headers: {
        'Content-Type': 'application/json'
      },
      data: JSON.stringify(jsonPayload)
    });

    // Check the response status code - expecting 201 if the resource creation is successful
    expect(postResponse.status()).toBe(201);

    // Parse the response data
    const postResponseBody = await postResponse.json();
    console.log('RESPONSE:', postResponseBody);

    // Validate the response properties - adapt as needed
    expect(postResponseBody).toHaveProperty('title', 'Architect');
    expect(postResponseBody).toHaveProperty('body', 'DW-BI');
    expect(postResponseBody).toHaveProperty('userId', 5);

  } catch (error) {
    if (error instanceof Error) {
      console.error('Error message:', error.message);
    } else {
      console.error('An unknown error occurred:', error);
    }
  }
});
import { test, expect } from '@playwright/test';
test('Send JSON file as payload', async ({ request })
const fs = require('fs');
// Read and parse JSON file directly into a JavaScript object
const jsonPayload = JSON.parse(fs.readFileSync('tests/payloads/jsonpayload.json', 'utf8'));

console.log('JSON data parsed successfully:', jsonPayload);
 // Perform a POST request
    const postResponse = await request.post('https://jsonplaceholder.typicode.com/users', {
      headers: {
        'Content-Type': 'application/json'
      },
      data: JSON.stringify(jsonPayload)
    });
expect(postResponse.status()).toBe(201);
// Parse the response data
const postResponseBody = await postResponse.json();
console.log(postResponseBody);
// Validate the response properties - adapt as needed
expect(postResponseBody).toHaveProperty('title', 'Architect');
expect(postResponseBody).toHaveProperty('body', 'DW-BI');
expect(postResponseBody).toHaveProperty('userId', 5);

npx playwright test api_json_payload.spec.ts

npx playwright show-report

Leave a comment