Tester JB
Tester JB

Reputation: 61

How to assert the value of the preselected value from a dropdown using Playwright? Typescript

How to assert the value of the preselected value from a dropdown using Playwright? Typescript

I am using the below code to assert the preselected value of a dropdown.

const dropdownValue = await this.page.$eval<string, HTMLSelectElement>("#recommendations_recommendation", ele => ele.value);
    expect(dropdownValue).toBe("Approve");

I am getting the below error in the console:-

Error: expect(received).toBe(expected) // Object.is equality

    Expected: "Approve"
    Received: ""

The webelement locator is correct i.e. the CSS path. Not sure why it is throwing me error. Can anyone please help me here to get the value of the dropdown?

Upvotes: 2

Views: 2998

Answers (2)

Tom Parkinson
Tom Parkinson

Reputation: 11

Not sure that this will suit everyone, but an alternative I've stumbled on is to use the css pseudo-class 'checked' (https://developer.mozilla.org/en-US/docs/Web/CSS/:checked) for both checkboxes and select inputs:

const selectedOption = page.getByTestId('select-input').locator('option:checked');

This has the advantage of not restricting you to inputValue which may have nothing to do with the text visible to the user.

This was after experimenting with:

const selectedOption = page.getByTestId('select-input').locator('option[selected="selected"]');

The above solution seems to be in a few places around the internet when searching for playwright assert selected option but wasn't returning anything for me after setting the selected option with selectOption, where :checked works fine (however, if the option in question is rendered as selected, then the selected="selected" does work, as does getAttribute('selected')).

Upvotes: 1

Alapan Das
Alapan Das

Reputation: 18618

You can do like this:

const locator = page.locator('#recommendations_recommendation');
await expect(locator).toHaveValue('Approve');

You can try asserting the inner text:

const locator = page.locator('#recommendations_recommendation');
await expect(locator).toHaveText('Approve');

Upvotes: 1

Related Questions