Machtyn
Machtyn

Reputation: 3272

how to validate multiple selections on a select element in playwright nodejs

I'm having a hard time getting playwright to validate multiple selections in a multiple select element.

For example, say I have the following multiple select:

<select id="colors" name="selected-colors" multiple>
  <option value="R">Red</option>
  <option value="Y">Yellow</option>
  <option value="B">Blue</option>
</select>

In my playwright script, I issue the following command:

await page.selectOption('#colors', ['R', 'B']);

So, at this time, the Red and Blue options are selected. In my app, the requirement is that after the user makes their selection, runs their report and lands on a new page, they should be able to back to this page and those options are still selected. So, I need to test that.

I've tried

await expect(page.locators('#colors')).toHaveValue(['R', 'B']);

But that isn't working for me. When I do that, it tells me the actual value is R. I've tried looking for an answer, but have not had any luck with it.

Upvotes: 1

Views: 1494

Answers (1)

Gaj Julije
Gaj Julije

Reputation: 2183

Even it not highly recommended by playwright team, I am not sure that you have much choice rather then use "$eval".

const allSelectedValues = await page.$eval('yourMultiSelectorLocator', e => Array.from(e.selectedOptions).map(option => option.value));

expect(selectedValues).toEqual(['R', 'B']);

Upvotes: 1

Related Questions