reactjsreact-nativeplaywrightnative-base

Selecting a native-base `<Select>` option using Playwright


I am trying to use Playwright to select a Native-Base <Select> option, but I don't know how to reference the HTML <select> input created by this component.

My React Native code looks like this:

<Select
  testID="nb-select-component"
  defaultValue="yes"
>
  <Select.Item label="Yes" value="yes" />
  <Select.Item label="No" value="no" />
</Select>

This renders in HTML as something like this:

<div>
  <select>
    <option value="yes">Yes</option>
    <option value="no">No</option>
  </select>
  <div>
    <input readonly type="hidden" data-testid="nb-select-component" />
  </div>
</div>

Notice that the testID propagates into an <input readonly /> element, not to the <select> element.

If I could grab the <select> HTML element, my Playwright code would look something like this:

const selectElement = page.locator("data-testid=html-select-element");
await selectElement.selectOption({ "value": "yes" });

However I don't know how to access the <select> HTML element or change the value of the <Select> native-base component from Playwright.


Solution

  • Playwright supports XPath queries, so if I isolate the <input data-testid="nb-select-component" />, I can use Xpath to retrieve the <select> element from the grandparent's <div> like this:

    const selectElement = page.locator(
      '//input[@data-testid="html-select-element"]' + // xpath to <input>
      '../../select' // grandparent's first child: <select>
    );
    await selectElement.selectOption({ "value": "yes" });