Reputation: 83
I'm trying to validate the dropdown value I selected. I'm using this for the Playwright tool. I wrote a code for that validation but I got an error. anyone knows how to fix this error and how to write this in typescript using this $eval. thank you.
test('testing Drop Down',async ({page}) => {
await page.goto('https://the-internet.herokuapp.com/dropdown');
await page.selectOption('#dropdown','1');
const selectvalue = await page.$eval('#dropdown',(element)=>element.value);
expect (selectvalue).toContain('1');
Error: expect(received).toContain(expected) // indexOf
Expected substring: "1"
Received string: "select"
22 | // const alloption=await option1.$$('option');
23 | await page.locator('select').selectOption('1');
> 24 | await expect('select').toContain('1')
| ^
25 |
26 |
Upvotes: 3
Views: 11205
Reputation: 4207
Here's how you can validate the selected value in a drop-down:
import { test, expect } from '@playwright/test';
test('validate drop-down value', async ({ page }) => {
// Navigate to the desired URL
await page.goto('https://your-site.com');
// Select a value from the drop-down
await page.selectOption('#dropdown_id', 'option_value');
// Retrieve & verify the selected value using locator
const locator = page.locator('#dropdown_id');
await expect(locator).toHaveValue(expectedValue);
console.log('Drop-down value is validated! Now Go out and have some fun!!!');
});
Upvotes: 1
Reputation: 169
May use evaluate https://playwright.dev/docs/next/api/class-worker#worker-evaluate
locator.evaluate("el => el.options[el.selectedIndex].value")
Upvotes: 2
Reputation: 2183
I had similar issues on that page sometimes it is going faster and pick select as default, even the code after is changing the dd to some other values. So you can use hard wait.
page.waitforTimeout(100)
or this:
selectedDDtext = page.locator('#dropdown [selected="selected"]');
texttoVerify = selectedDDtext.innerText();
Or for value:
await this.page.$eval<string, HTMLSelectElement>('select[id="dropdown"]',(ele) => ele.value);
Upvotes: 3