Lesson 1
Automating Dropdown Selection
Introduction to Automating Dropdown Selection

Welcome to an exciting part of our course where we delve into automating dropdown selections using Playwright. Dropdowns are common on web pages for user selections, such as choosing a category of books or filtering search results. This lesson will guide you through writing automated tests to interact with dropdowns, enhancing your Playwright skills.

Key Concepts and Techniques

In this lesson, you will learn how to automate dropdown selection with Playwright. We'll cover the process of identifying and interacting with dropdown elements on a webpage to select a specific option. Here's a sneak peek:

TypeScript
1import { test, expect } from '@playwright/test'; 2 3test('automate dropdown selection', async ({ page }) => { 4 await page.goto('http://localhost:3000/books'); 5 await page.selectOption('select#categories', 'Fantasy'); 6 7 const selectedValue = await page.$eval('select#categories', select => select.value); 8 expect(selectedValue).toBe('Fantasy'); 9 10 await expect(page.locator('.book-title >> text=Harry Potter and the Philosopher\'s Stone')).toBeVisible(); 11 await expect(page.locator('.book-title >> text=The Hobbit')).toBeVisible(); 12 await expect(page.locator('.book-title >> text=The Great Gatsby')).not.toBeVisible(); 13});

In this test, we perform the following actions:

  1. Navigate to a Web Page: Using page.goto('http://localhost:3000/books'), Playwright opens the specified URL, which hosts the dropdown we want to manipulate.

  2. Select an Option from a Dropdown: We use page.selectOption('select#categories', 'Fantasy') to automate the action of selecting the 'Fantasy' option. The CSS selector select#categories is used to fetch the 'select' element with an id of 'categories', which corresponds to an HTML element like <select id="categories"…>. This simulates the user action of choosing an option from the dropdown.

  3. Verify the Selected Value: By evaluating the current value of the dropdown with page.$eval('select#categories', select => select.value), we ensure it's set to 'Fantasy'. This serves as a check to confirm that the selection occurred as expected.

    • The page.$eval method fetches the element matching the CSS selector 'select#categories', which is the dropdown element.
    • The arrow function select => select.value then takes this element as input and returns its value attribute.
  4. Expectations for Page Content: We employ expect assertions to check that specific content is visible on the page following the selection. Specifically, we assert that elements with classes '.book-title' containing the texts 'Harry Potter and the Philosopher's Stone' and 'The Hobbit' are visible, and that 'The Great Gatsby' is not visible. This confirms that selecting 'Fantasy' filters the page contents correctly.

These steps collectively demonstrate how to automate dropdown selection in Playwright, confirming that the webpage's filtering functionality responds accurately after interaction.

Retrieving All Possible Dropdown Options

In addition to selecting a specific option, it can be beneficial to understand how to retrieve all possible options from a dropdown. This assists in scenarios where you need to verify the presence of certain options or dynamically interact with them.

TypeScript
1import { test, expect } from '@playwright/test'; 2 3test('retrieve all dropdown options', async ({ page }) => { 4 await page.goto('http://localhost:3000/books'); 5 6 const expectedOptions = ['', 'Literature', 'Science Fiction', 'Fantasy']; 7 8 const options = await page.$$eval('select#categories option', options => options.map(option => option.value)); 9 10 expect(options).toEqual(expectedOptions); 11});

In this example, we perform the following actions:

  1. Navigate to a Web Page: Just like selecting an option, we first navigate to the desired page using page.goto('http://localhost:3000/books').

  2. Understand Arrays: Arrays are used to store multiple items in a single variable and are defined using square brackets []. In the code, the array expectedOptions is initialized as const expectedOptions = ['', 'Literature', 'Science Fiction', 'Fantasy'];, containing the list of expected dropdown values. This list will be then used to compare and verify the list of options that we get from the page.

  3. Retrieve All Options: We use page.$$eval('select#categories option', options => options.map(option => option.value)) to fetch all option elements within the dropdown. The CSS selector select#categories option targets each option under the dropdown. This returns an array of option values.

    • Notice that we use $$eval here instead of $eval: $eval is used to select a single element and execute a function on it, while $$eval is used to select all matching elements and apply a function to an array of those elements.
    • The map function is used to create a new array containing the values of each 'option' element. It iterates over the array of 'option' elements and extracts their 'value' attribute.
    • CSS selectors separated by spaces are known as descendant selectors. They target elements that are descendants of a specified ancestor in the HTML structure. The space between two selectors indicates that the second selector is a descendant, not necessarily a direct child, of the element targeted by the first selector. Consider the selector select#categories option used in our Playwright example:
      • select#categories: This part selects the <select> element with the id of 'categories'.
      • option: Following the space, this part selects <option> elements that are descendants (at any level) of the <select> element. It doesn't matter how many levels down the <option> elements are; as long as they are nested within the <select>, they will be targeted.
  4. Verify Options Content: By comparing the retrieved options array with an expectedOptions array using expect(options).toEqual(expectedOptions), we ensure that the options in the dropdown match the expected set of categories. The toEqual assertion checks that the arrays are equal in both content and order, ensuring that the dropdown includes all required categories in a precise sequence.

This technique provides a robust way to verify the exact set of dropdown options, ensuring that the dropdown includes all required categories in a precise order.

Arrow functions

Arrow functions in JavaScript allow you to describe a task or behavior in a clear and straightforward way using the => symbol.

Here's how they work:

  1. Parameters: These are like placeholders. When you write an arrow function, you may use parentheses () to list what the function needs to perform its task. For example, if you want to add two numbers, you'll have parameters for those numbers:

    JavaScript
    1const add = (a, b) => a + b;

    Here, a and b are parameters.

  2. Task: After the parameters, an arrow function shows what it does using the => symbol. In the example above, a + b is the task of adding the two numbers.

In our Playwright examples, let's see arrow functions in action:

  • In page.$eval('select#categories', select => select.value), select => select.value is an arrow function. Here, select acts as a placeholder for the dropdown element, and select.value describes the task of getting the dropdown's value.

  • In page.$$eval('select#categories option', options => options.map(option => option.value)), options.map(option => option.value) uses placeholders option to represent each dropdown option, describing how to get each option's value.

Arrow functions provide a simple way to describe a task, focusing on what you want to achieve without adding extra complexity.

Why It Matters

Automating dropdown selections is crucial for creating robust automated tests. It ensures that web applications function correctly across a variety of user interactions, leading to improved user experiences and saving time in manual testing. Mastery of this skill will boost your efficiency in writing tests and handling dynamic web environments.

With this newfound knowledge, you're all set to move into the practice section. Let's put these concepts into action and deepen your understanding!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.