In this lesson, Artem Bondar explains how to automate the selection of dates in date pickers using Playwright, and how to validate the date value inside the input field. Here is a step-by-step breakdown of the process:
### Automating Date Pickers
#### Step 1: Navigate to the Date Picker Page
- **Code**:
```javascript
await page.goto('URL/forms-and-date-picker');
```
#### Step 2: Locate the Date Picker Input Field
- **Inspect Element**: Identify the placeholder for the date picker input field.
- **Code**:
```javascript
const calendarInputField = page.getByPlaceholder('Form Picker');
await calendarInputField.click();
```
#### Step 3: Select a Date in the Calendar
- **Inspect Element**: Identify the structure of the calendar and differentiate between the current month and other months by their class names.
- **Code**:
```javascript
// Locate all date cells of the current month (June)
const currentMonthDays = page.locator('.day-cell.in-month');
// Select a specific date, e.g., June 14
await currentMonthDays.getByText('14').click();
```
#### Step 4: Handle Partial Matches
- **Issue**: Selecting the 1st of the month results in multiple matches due to partial text matches.
- **Solution**: Use the `exact` flag to ensure an exact match.
- **Code**:
```javascript
await currentMonthDays.getByText('1', { exact: true }).click();
```
#### Step 5: Validate the Date in the Input Field
- **Code**:
```javascript
await expect(calendarInputField).toHaveValue('June 1, 2023');
```
### Full Test Example
```javascript
test('Automate Date Picker', async ({ page }) => {
// Step 1: Navigate to the Date Picker Page
await page.goto('URL/forms-and-date-picker');
// Step 2: Locate the Date Picker Input Field
const calendarInputField = page.getByPlaceholder('Form Picker');
await calendarInputField.click();
// Step 3: Select a Date in the Calendar
const currentMonthDays = page.locator('.day-cell.in-month');
// Handle Partial Matches by Using the exact flag
await currentMonthDays.getByText('1', { exact: true }).click();
// Step 5: Validate the Date in the Input Field
await expect(calendarInputField).toHaveValue('June 1, 2023');
});
```
### Summary
- **Selecting Dates**: Identify unique locators that represent the date cells for the current month, and use the `exact` flag to ensure precise selection.
- **Validation**: Use locator assertions to confirm the date value displayed in the input field matches the selected date.
By following these steps, you can automate the process of selecting dates in date pickers and validating the selected date using Playwright.
Comments are closed.