Run Playwright Java tests in headed mode

HOME

launch(new BrowserType.LaunchOptions().setHeadless(false));

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

import java.util.regex.Pattern;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

public class PlaywrightDemo {

    public static void main(String[] args) {

        try (Playwright playwright = Playwright.create()) {

            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            Page page = browser.newPage();
            page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
            page.waitForTimeout(2000);
            System.out.println("Title :" + page.title());
            assertThat(page).hasTitle(Pattern.compile("OrangeHRM"));
        }
    }
}

(Playwright playwright = Playwright.create()) 
Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
Page page = browser.newPage();
page.navigate("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
page.waitForTimeout(2000);
System.out.println("Title :" + page.title());
assertThat(page).hasTitle(Pattern.compile("OrangeHRM"));

Web Automation Testing with Playwright Java

HOME

<!-- https://mvnrepository.com/artifact/com.microsoft.playwright/playwright -->
<dependency>
    <groupId>com.microsoft.playwright</groupId>
    <artifactId>playwright</artifactId>
    <version>1.57.0</version>
</dependency>

import com.microsoft.playwright.Browser;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

import java.util.regex.Pattern;

import static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;

public class PlaywrightDemo {

    public static void main(String[] args) {

        try (Playwright playwright = Playwright.create()) {

            Browser browser = playwright.chromium().launch();
            Page page = browser.newPage();
            page.navigate("https://qaautomation.expert/");
            System.out.println("Title :" + page.title());
            assertThat(page).hasTitle(Pattern.compile("QA Automation Expert"));
        }
    }
}
  try (Playwright playwright = Playwright.create()) 
Browser browser = playwright.chromium().launch();
 Page page = browser.newPage();
page.navigate("https://qaautomation.expert/");
System.out.println("Title :" + page.title());
assertThat(page).hasTitle(Pattern.compile("QA Automation Expert"));

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

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

How to Execute DELETE 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 - DELETE with Playwright', async ({ request }) => {

// Perform a DELETE request
const response = await request.delete('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);
     
   });
import { test, expect } from '@playwright/test';
test('API Testing - DELETE with Playwright', async ({ request }) => {
const response = await request.delete('https://jsonplaceholder.typicode.com/posts/1');
expect(response.status()).toBe(200);
 const responseBody = await response.json();
console.log(responseBody);

npx playwright test api_delete_tests.spec.ts

npx playwright show-report

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