How to Execute PATCH Requests in Playwright

HOME

npm install playwright

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

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

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

test('API Testing - PATCH with Playwright', async ({ request }) => {

const response = await request.get('https://jsonplaceholder.typicode.com/posts/1');
      
    // Check the response status code 
    expect(response.status()).toBe(200);

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

  
     // Perform a PATCH request
     const patchResponse = await request.patch('https://jsonplaceholder.typicode.com/posts/1', {
       data: {
         title: 'Manager'
       }
     });

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

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

    // Validate the response 
    expect(patchResponseBody).toHaveProperty('title', 'Manager');

   });

This line imports the `test` and `expect` functions from the Playwright testing module. They provide a structure for creating tests and validating outcomes.

import { test, expect } from '@playwright/test';
test('API Testing - PATCH with Playwright', async ({ request }) => {
const patchResponse = await request.patch('https://jsonplaceholder.typicode.com/posts/1', {
      data: {
        title: 'Manager'
      }
    });
expect(patchResponse.status()).toBe(200);
const patchResponseBody = await patchResponse.json();
console.log(patchResponseBody);
expect(patchResponseBody).toHaveProperty('title', 'Manager');

npx playwright test api_patch_tests.spec.ts

npx playwright show-report

Mastering Snapshot Testing with Playwright

HOME

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

test('snapshot test example', async ({ page }) => {
    
    // Navigate to the page you want to test
     await page.goto('https://playwright.dev/');

     // Capture a snapshot of the whole page
     const screenshot = await page.screenshot();

     // Compare the screenshot to a stored baseline snapshot
     expect(screenshot).toMatchSnapshot('login_page.png');
  
    });

npx playwright test snapshot_fullpage_tests.spec.ts

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

test('snapshot test example', async ({ page }) => {

    // Navigate to the page you want to test
    await page.goto('https://playwright.dev/');

    // Select the specific UI component using a locator method
    const component = await page.locator('//*[@id="__docusaurus_skipToContent_fallback"]/header/div/h1/span'); 
    
    // Capture a snapshot of a component in the page
    const screenshot = await component.screenshot();

    // Compare the screenshot to a stored baseline snapshot
    expect(screenshot).toMatchSnapshot('Title.png');

});

Unlocking Playwright: Test Reports with Tags and Annotations

HOME

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

/**
 * See https://playwright.dev/docs/test-configuration.
 */
export default defineConfig({
  testDir: './tests',

 /* Run tests in files in parallel */
  fullyParallel: true,
 
 /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: 'html',
 
 /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry'

  },

  /* Configure projects for major browsers */
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },

  ]

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

test('has title', async ({ page, browserName }) => {
  await page.goto('https://opensource-demo.orangehrmlive.com/');

  // Print the browser name
  console.log(`Running test on browser: ${browserName}`);

  // Expect a title "to contain" a substring.
  await expect(page).toHaveTitle(/OrangeHRM/);
});


test('valid login', async ({ page, browserName }) => {

  const username = 'Admin';
  const password = 'admin123'

  await page.goto('https://opensource-demo.orangehrmlive.com/');

  // Print the browser name
  console.log(`Running test on browser: ${browserName}`);

  // Fill in the username
  await page.fill('input[name="username"]', username);

  // Fill in the password
  await page.fill('input[name="password"]', password);

  // Click the login button - Use XPath to locate and click the login button
  const loginButton = await page.locator('//button[@type="submit" and contains(@class, "orangehrm-login-button")]').click();

  // Get the text content from the element
  const dashboardText = await page.locator('//h6[contains(@class, "oxd-topbar-header-breadcrumb-module")]').textContent();

  // Print the text
  console.log(`Dashboard text: ${dashboardText}`);

  expect(dashboardText).toContain('Dashboard');

});


test('invalid username', async ({ page, browserName }) => {

  const username = 'Admin123';
  const password = 'admin123'

  await page.goto('https://opensource-demo.orangehrmlive.com/');

  // Print the browser name
  console.log(`Running test on browser: ${browserName}`);

  // Fill in the username
  await page.fill('input[name="username"]', username);

  // Fill in the password
  await page.fill('input[name="password"]', password);

  // Click the login button - Use XPath to locate and click the login button
  const loginButton = await page.locator('//button[@type="submit" and contains(@class, "orangehrm-login-button")]').click();

  // Get the text content from the element
  const actualErrorMessage = await page.locator('//p[contains(@class, "oxd-alert-content-text") and text()="Invalid credentials"]').textContent();

  // Print the text
  console.log(`Dashboard text: ${actualErrorMessage}`);

  expect(actualErrorMessage).toContain('Invalid credentials');

});
test.skip('invalid username',  async ({ page, browserName }) => {
//
}

test.fail('invalid username',  async ({ page, browserName }) {
//
}

test.fixme('invalid username',  async ({ page, browserName }) => { 
//
}

It marks the test as slow and triples the test timeout.

test.slow('invalid username',  async ({ page, browserName }) => { 
//
}
test.only('invalid username',  async ({ page, browserName }) => {
//
}
test('skip this test', async ({ page, browserName }) => {
  test.skip(browserName === 'firefox', 'Still working on it');
});
test.describe('login check',() => {
test('valid login', async ({ page, browserName }) => {

  const username = 'Admin';
  const password = 'admin123'

  await page.goto('https://opensource-demo.orangehrmlive.com/');
  console.log(`Running test on browser: ${browserName}`);

  await page.fill('input[name="username"]', username);
  await page.fill('input[name="password"]', password);

  const loginButton = await page.locator('//button[@type="submit" and contains(@class, "orangehrm-login-button")]').click();

  const dashboardText = await page.locator('//h6[contains(@class, "oxd-topbar-header-breadcrumb-module")]').textContent();

  console.log(`Dashboard text: ${dashboardText}`);
  expect(dashboardText).toContain('Dashboard');

});


test('invalid username',  async ({ page, browserName }) => {

  const username = 'Admin123';
  const password = 'admin123'

  await page.goto('https://opensource-demo.orangehrmlive.com/');
  console.log(`Running test on browser: ${browserName}`);

  await page.fill('input[name="username"]', username);
  await page.fill('input[name="password"]', password);

  const loginButton = await page.locator('//button[@type="submit" and contains(@class, "orangehrm-login-button")]').click();

  const actualErrorMessage = await page.locator('//p[contains(@class, "oxd-alert-content-text") and text()="Invalid credentials"]').textContent();

  console.log(`Dashboard text: ${actualErrorMessage}`);
  expect(actualErrorMessage).toContain('Invalid credentials');

});

});

test('invalid username',   {
  tag: '@fast',
}, async ({ page, browserName }) => {
//
}

npx playwright test --grep "@fast"

npx playwright test login_page.spec.ts --grep-invert "@fast"
npx playwright test --grep --% "@fast^|@slow"
npx playwright test --grep "(?=.*@fast)(?=.*@slow)"

How to Execute PUT Requests in Playwright

HOME

npm install playwright

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

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

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

 test('API Testing - PUT with Playwright', async ({ request }) => {

    // Perform a GET request
    const response = await request.get('https://jsonplaceholder.typicode.com/posts/1');
      
     // Check the response status code
     expect(response.status()).toBe(200);

     // Parse the response data
     const responseBody = await response.json();
     console.log(responseBody);
  
     // Perform a PUT request
     const putResponse = await request.put('https://jsonplaceholder.typicode.com/posts/1', {
       data: {
         title: 'Manager',
         body: 'Test',
         userId: 1
       }
     });

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

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

     // Validate the response
     expect(putResponseBody).toHaveProperty('title', 'Manager');
     expect(putResponseBody).toHaveProperty('body', 'Test');
     expect(putResponseBody).toHaveProperty('userId', 1);
   });
import { test, expect } from '@playwright/test';
test('API Testing - PUT with Playwright', async ({ request }) 
 // Perform a GET request
    const response = await request.get('https://jsonplaceholder.typicode.com/posts/1');
      
     // Check the response status code
     expect(response.status()).toBe(200);

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

const putResponse = await request.put('https://jsonplaceholder.typicode.com/posts/1', {
       data: {
         title: 'Manager',
         body: 'Test',
         userId: 1
       }
 });
expect(putResponse.status()).toBe(200);
const putResponseBody = await putResponse.json();
console.log(putResponseBody);
expect(putResponseBody).toHaveProperty('title', 'Manager');
expect(putResponseBody).toHaveProperty('body', 'Test');
expect(putResponseBody).toHaveProperty('userId', 1);

npx playwright test api_put_tests.spec.ts

npx playwright show-report

How to Execute POST Requests in Playwright

HOME

What is POST Request?

npm install playwright

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

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

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

 test('API Testing - POST with Playwright', async ({ request }) => {

     // Perform a POST request
     const postResponse = await request.post('https://jsonplaceholder.typicode.com/users', {
       data: {
         title: 'Manager',
         body: 'Test',
         userId: 10,
       }
     }); 

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

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

     // Validate the response
     expect(postResponseBody).toHaveProperty('title', 'Manager');
     expect(postResponseBody).toHaveProperty('body', 'Test');
     expect(postResponseBody).toHaveProperty('userId', 10);
   });
import { test, expect } from '@playwright/test';
test('API Testing - POST with Playwright', async ({ request }) 
 const postResponse = await request.post('https://jsonplaceholder.typicode.com/users', {
       data: {
         title: 'Manager',
         body: 'Test',
         userId: 10,
       }
     }); 
expect(postResponse.status()).toBe(201);
const postResponseBody = await postResponse.json();
console.log(postResponseBody);

The assertions verify that the response contains expected data.

expect(postResponseBody).toHaveProperty('title', 'Manager');
expect(postResponseBody).toHaveProperty('body', 'Test');
expect(postResponseBody).toHaveProperty('userId', 10);

npx playwright test api_post_tests.spec.ts

npx playwright show-report

How to Execute GET Requests in Playwright

HOME

npm install playwright

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

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

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

test('API Testing - GET with Playwright', async ({ request }) => {

     // Perform a GET request
     const response = await request.get('https://jsonplaceholder.typicode.com/users/1');
      
     // 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
     expect(responseBody).toHaveProperty('id', 1);
     expect(responseBody).toHaveProperty('name','Leanne Graham');
     expect(responseBody).toHaveProperty('address.zipcode','92998-3874');
     expect(responseBody).toHaveProperty('address.geo.lat','-37.3159');

   });
import { test, expect } from '@playwright/test';
test('API Testing - GET with Playwright', async ({ request }) => {
 const response = await request.get('https://jsonplaceholder.typicode.com/users/1');
 expect(response.status()).toBe(200);
 const responseBody = await response.json();
console.log(responseBody);
expect(responseBody).toHaveProperty('id', 1);
expect(responseBody).toHaveProperty('name','Leanne Graham');
expect(responseBody).toHaveProperty('address.zipcode','92998-3874');
expect(responseBody).toHaveProperty('address.geo.lat','-37.3159');

npx playwright test api_get_tests.spec.ts

npx playwright show-report

How to Attach Screenshots in Playwright for Failed Tests

HOME

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

export default defineConfig({
  
  testDir: './tests',

  /* Retries each failed test 1 time automatically */
  retries: 0,  

  /* Run tests in files in parallel */
  fullyParallel: true,
  
  /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: 'html',
  
  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry',

    headless: false,
    
    screenshot: 'only-on-failure',
  },

  /* Configure projects for major browsers */
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },

     ],

});

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

test('has title', async ({ page, browserName }) => {
  await page.goto('https://opensource-demo.orangehrmlive.com/');

  // Print the browser name
  console.log(`Running test on browser: ${browserName}`);  

  // Expect a title "to contain" a substring.
  await expect(page).toHaveTitle(/OrangeHRM/);
});


test('valid login', async ({ page, browserName }) => {

  const username = 'Admin';
  const password = 'admin123'

  await page.goto('https://opensource-demo.orangehrmlive.com/');

  // Print the browser name
  console.log(`Running test on browser: ${browserName}`);  

  // Fill in the username
   await page.fill('input[name="username"]', username);
  
  // Fill in the password
  await page.fill('input[name="password"]', password);

  // Click the login button - Use XPath to locate and click the login button
  const loginButton = await page.locator('//button[@type="submit" and contains(@class, "orangehrm-login-button")]').click();

  // Get the text content from the element
  const dashboardText = await page.locator('//h6[contains(@class, "oxd-topbar-header-breadcrumb-module")]').textContent();
  
  // Print the text
  console.log(`Dashboard text: ${dashboardText}`);
  
  expect(dashboardText).toContain('Dashboard1');

});

npx playwright test login_page.spec.ts

Automate Playwright Tests with Command-Line Options

HOME

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

/**
 * See https://playwright.dev/docs/test-configuration.
 */
export default defineConfig({
  testDir: './tests',

 /* Run tests in files in parallel */
  fullyParallel: true,
 
 /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: 'html',
 
 /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry'

  },

  /* Configure projects for major browsers */
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },

    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },

    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    } 

  ]

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

test('has title', async ({ page, browserName }) => {
  await page.goto('https://playwright.dev/');

  // Print the browser name
  console.log(`Running test on browser: ${browserName}`);  

  // Expect a title "to contain" a substring.
  await expect(page).toHaveTitle(/Playwright/);

});

test('get started link', async ({ page, browserName }) => {
  await page.goto('https://playwright.dev/');

  // Print the browser name
  console.log(`Running test on browser: ${browserName}`); 

  // Click the get started link.
  await page.getByRole('link', { name: 'Get started' }).click();

  // Expects page to have a heading with the name of Installation.
  await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();
});

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

test('has title', async ({ page, browserName }) => {
  await page.goto('https://opensource-demo.orangehrmlive.com/');

  console.log(`Running test on browser: ${browserName}`);  // Print the browser name

  // Expect a title "to contain" a substring.
  await expect(page).toHaveTitle(/OrangeHRM/);
});


test('valid login', async ({ page, browserName }) => {

  const username = 'Admin';
  const password = 'admin123'

  await page.goto('https://opensource-demo.orangehrmlive.com/');

  // Print the browser name
  console.log(`Running test on browser: ${browserName}`);  

  // Fill in the username
   await page.fill('input[name="username"]', username);

  // Fill in the password
    await page.fill('input[name="password"]', password);

  // Click the login button - Use XPath to locate and click the login button
  const loginButton = page.locator('//button[@type="submit" and contains(@class, "orangehrm-login-button")]');
  await loginButton.click();

  // Check if the page contains text Dashboard - Locate the element using XPath
  const dashboardElement = await page.locator('//h6[contains(@class, "oxd-topbar-header-breadcrumb-module")]');

  // Get the text content from the element
  const dashboardText = await dashboardElement.textContent();
  
  // Print the text
  console.log(`Dashboard text: ${dashboardText}`);
  
  expect(dashboardText).toContain('Dashboard');
});
npx playwright test

npx playwright test login_page.spec.ts

npx playwright test example 

npx playwright test -g "valid login"

npx playwright test --list

How to Run Playwright Tests in UI Mode

HOME

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

/**
 * See https://playwright.dev/docs/test-configuration.
 */

export default defineConfig({
  testDir: './tests',
  
  /* Run tests in files in parallel */
  fullyParallel: true,
 
  /* Opt out of parallel tests on CI. */
  workers: process.env.CI ? 1 : undefined,
  
  /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: 'html',
 
 /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {

   // Running tests in UI mode
    headless: false
  }

});

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

test('has title', async ({ page, browserName }) => {
  await page.goto('https://playwright.dev/');

   console.log(`Running test on browser: ${browserName}`);  // Print the browser name

  // Expect a title "to contain" a substring.
  await expect(page).toHaveTitle(/Playwright/);
});

test('get started link', async ({ page, browserName }) => {
  await page.goto('https://playwright.dev/');

   console.log(`Running test on browser: ${browserName}`);  // Print the browser nameÓ

  // Click the get started link.
  await page.getByRole('link', { name: 'Get started' }).click();

  // Expects page to have a heading with the name of Installation.
  await expect(page.getByRole('heading', { name: 'Installation' })).toBeVisible();
});

npx playwright test --ui

How to Specify Browsers in Playwright Tests

HOME

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

/**
 * See https://playwright.dev/docs/test-configuration.
 */
export default defineConfig({
  testDir: './tests',

 /* Run tests in files in parallel */
  fullyParallel: true,
 
 /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: 'html',
 
 /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry'

  },

  /* Configure projects for major browsers */
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    }
  ]

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

/*test.afterEach(async ({ page }, testInfo) => {
    // Take screenshot after each test
    if (testInfo.status !== testInfo.expectedStatus) {
      // If the test failed, capture a screenshot
      await page.screenshot({
        path: `Failed-Tests/screenshots/${testInfo.title.replace(/\s+/g, '_')}.png`,
        fullPage: true
      });
    }
  }); */

test('has title', async ({ page, browserName }) => {
  await page.goto('https://opensource-demo.orangehrmlive.com/');

  console.log(`Running test on browser: ${browserName}`);  // Print the browser name

  await page.waitForTimeout(3000); // Wait for 3 seconds

  // Expect a title "to contain" a substring.
  await expect(page).toHaveTitle(/OrangeHRM/);
});


test('valid login', async ({ page, browserName }) => {

  const username = 'Admin';
  const password = 'admin123'

  await page.goto('https://opensource-demo.orangehrmlive.com/');

  // Print the browser name
  console.log(`Running test on browser: ${browserName}`);  

  // Fill in the username
   await page.fill('input[name="username"]', username);
  
  // Print the username
  console.log(`Logging in with username: ${username}`);

  // Fill in the password
  await page.fill('input[name="password"]', password);

  // Print the password
  console.log(`Logging in with password: ${password}`);

  // Click the login button - Use XPath to locate and click the login button
  const loginButton = await page.locator('//button[@type="submit" and contains(@class, "orangehrm-login-button")]').click();

  // Get the text content from the element
  const dashboardText = await page.locator('//h6[contains(@class, "oxd-topbar-header-breadcrumb-module")]').textContent();
  
  // Print the text
  console.log(`Dashboard text: ${dashboardText}`);
  
  expect(dashboardText).toContain('Dashboard');

});

npx playwright test login_page.spec.ts --project webkit

npx playwright test login_page.spec.ts --project webkit --project firefox

npx playwright test login_page.spec.ts
import { defineConfig, devices } from '@playwright/test';

/**
 * See https://playwright.dev/docs/test-configuration.
 */
export default defineConfig({
  testDir: './tests',

 /* Run tests in files in parallel */
  fullyParallel: true,
 
 /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: 'html',
 
 /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {

    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry'

  },

  /* Configure projects for major browsers */
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },

    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },

    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    } 
  ]
});