Search code examples
typescriptplaywrightplaywright-test

Playwright - Select dynamic dropdown options


I am trying to select a dropdown option that is dependent on entering a postal code. Below is what I done

 const postcode = page.locator("#postalCode");
  const findAddress = page.getByText("Find address", {exact: true});
  const selectAddress = page.locator("#addressSelection");

 await postcode.fill("GU22 7SS");
  await findAddress.click();
  await selectAddress.selectOption("37 The Rowans");

The URL I am using is: https://app.pws.int.cruk.org/support-us/details

I tried to explicitly tell playwright what option to select however, it times out with the following error:

  Error: locator.selectOption: Target closed
    =========================== logs ===========================
    waiting for locator('#addressSelection')
      locator resolved to <select aria-invalid="false" id="addressSelection" name=…>…</select>
      selecting specified option(s)
        did not find some options - waiting... 
    ============================================================

      48 |   await postcode.fill("GU22 7SS");
      49 |   await findAddress.click();
    > 50 |   await selectAddress.selectOption("37 The Rowans");
         |                       ^
      51 |
      52 |
      53 |

Can someone help me please?


Solution

  • For this option:

    <option value="GB|RM|A|10271328" data-option="Address">37 The Rowans, Woking, GU22 7SS</option>
    

    Try using an exact label in your selectOption argument:

    import {test} from "@playwright/test"; // ^1.39.0
    
    test("User can make a donation", async ({page}) => {
      const url = "<Your URL>";
      await page.goto(url, {waitUntil: "domcontentloaded"});
    
      const postcode = page.locator("#postalCode");
      const findAddress = page.getByText("Find address", {exact: true});
      const selectAddress = page.locator("#addressSelection");
    
      await postcode.fill("GU22 7SS");
      await findAddress.click();
      await selectAddress.selectOption("37 The Rowans, Woking, GU22 7SS");
    });
    

    Or use a regex:

    await selectAddress.selectOption(/\b37 The Rowans\b/);
    

    Or use the value="GB|RM|A|10271328":

    await selectAddress.selectOption("GB|RM|A|10271328");
    

    Note that after you select an option, the <select> disappears and is replaced with a set of <input> elements that use parts of the option you selected to fill in the address line 1, town/city and country fields. Address line 1 is auto-filled with 37 The Rowans, which is what you're passing to selectOption. This may be the cause of some confusion.