Sunday, April 13, 2025

Working with Select dropdown in playwright

 Working with <select> dropdowns in Playwright is pretty straightforward. You can use the selectOption() method to interact with <select> elements.

Working with Select dropdown in playwright

When working with dropdowns in Playwright, you can select options using three primary methods: by value, label, & index. Below, we will demonstrate each method with practical examples.

Working with Select dropdown in playwright


 Syntax

await page.selectOption('select#dropdown-id', 'value');

  1. 'select#dropdown-id' — CSS selector for your <select> element.
  2. 'value' — the value attribute of the <option> you want to select.


 Select by Label or text

//Using Label
  await page.locator("#country").selectOption({ label: "India" });

 Select by value attribute

//Using Value
  await page.locator("#country").selectOption({ value: "CA" });


 Select by index

//Using index
  await page.locator("#country").selectOption({ index: 4 });


Example for Select Dropdown in playwright

Let’s consider a simple dropdown on a test page. Here’s how to interact with it:

Use selectOption() to select the dropdown.

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

test('Handle select dropdown', async ({page}) => {

  await page.goto('https://practice.expandtesting.com/dropdown');

  //Select dropdown value
  //Using Label
  await page.locator("#country").selectOption({ label: "India" });

  //Using Value
  await page.locator("#country").selectOption({ value: "CA" });

  //Using index
  await page.locator("#country").selectOption({ index: 4 });
  
  //get the count for total countries.
  await expect(await page.locator("#country option")).toHaveCount(252); 
   
});

Get selected value in select dropdown 

To get the selected value from a native <select> dropdown in Playwright, here's how you can do it:

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

test('Get selected value', async ({page}) => {

  await page.goto('https://practice.expandtesting.com/dropdown');
 
  //Using Label
  await page.locator("#dropdown").selectOption({ label: "Option 2" });

  //Get selected value
  const selectedValue = await page.locator('#dropdown').inputValue();
  expect(selectedValue).toEqual("2"); 
  
});


Get all options in select dropdown

To get all options from a native <select> dropdown in Playwright, here's how you can do it:

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

test('Get all select dropdown options', async ({page}) => {

  await page.goto('https://practice.expandtesting.com/dropdown');
 
  //Using Label
  const getAllOptions = await page.locator("#dropdown option").allTextContents();
  console.log(getAllOptions);
  
  //Assert to check all dropdown option
  const expected = [ 'Please select\n            an option', 'Option 1', 'Option 2' ];
  expect(getAllOptions).toEqual(expected); 
  
});




No comments:

Post a Comment