[Playwright Interview question #30]: Cách select dropdown list value trong Playwright?
Câu hỏi phỏng vấn #30: Can you explain how to select drop down list value in Playwright?
Trả lời mẫu:
1. Select by Value:
// HTML: <select id="country">
await page.selectOption('#country', 'us');
// Multiple values
await page.selectOption('#country', ['us', 'ca', 'mx']);
2. Select by Label:
// Select by visible text
await page.selectOption('#country', { label: 'United States' });
// Multiple labels
await page.selectOption('#country', [
{ label: 'United States' },
{ label: 'Canada' }
]);
3. Select by Index:
// Select first option (index 0)
await page.selectOption('#country', { index: 0 });
4. Using Locator:
const dropdown = page.locator('#country');
await dropdown.selectOption('us');
// Or chain
await page.locator('#country').selectOption({ label: 'United States' });
5. Get Selected Value:
// Get current selection
const selectedValue = await page.locator('#country').inputValue();
console.log('Selected:', selectedValue);
// Get selected text
const selectedText = await page.locator('#country option:checked').textContent();
6. Verify Dropdown Options:
// Get all options
const options = await page.locator('#country option').allTextContents();
expect(options).toContain('United States');
// Count options
const count = await page.locator('#country option').count();
expect(count).toBe(195);
7. Custom Dropdowns (not ):
// Click to open dropdown
await page.click('.custom-dropdown-trigger');
// Select from list
await page.click('.dropdown-item:has-text("United States")');
// Or use text selector
await page.click('text=United States');
8. Wait for Options to Load:
// Wait for options to populate
await page.waitForFunction(() => { const select = document.querySelector('#country');
return select && select.options.length > 0; });
await page.selectOption('#country', 'us');
💡 Tips:
- selectOption() works only với elements
- For custom dropdowns, use click() sequences
- Always verify selection after selecting
- Handle dynamic dropdowns với proper waits
Lời Kết
Playwright đang trở thành một trong những automation frameworks phổ biến nhất cho web testing. Thông qua series này, hy vọng bạn sẽ:
- Nắm vững kiến thức từ cơ bản đến nâng cao
- Tự tin trong các buổi phỏng vấn
- Áp dụng hiệu quả vào dự án thực tế
- Trở thành một phần của cộng đồng Playwright Việt Nam năng động
📚 Bắt đầu hành trình của bạn với: Bài 1: Playwright vs Selenium
💬 Có câu hỏi? Tham gia group Facebook của chúng mình!
⭐ Theo dõi series để không bỏ lỡ bài viết mới!
All rights reserved