Search code examples
angularplaywright

Playwright - how do I access an Angular 2-way binding model value with locator if I have multiple dropdowns of the same name?


I have multiple dropdowns with the same name and I am trying to access the currently selected values, which are 2-way bind using Angular. I am trying to compare if the currently displayed values are all set to complete as pictured: Validate dropdowns are set to Complete

The current html elements that the browser sees is:

<select _ngcontent-pis-c119="" name="dispo" class="dash-select ng-pristine ng-valid ng-touched"><option _ngcontent-pis-c119="" value="Active" class="ng-star-inserted"> Active </option><option _ngcontent-pis-c119="" value="On Hold" class="ng-star-inserted"> On Hold </option><option _ngcontent-pis-c119="" value="Completed" class="ng-star-inserted"> Completed </option><option _ngcontent-pis-c119="" value="Canceled" class="ng-star-inserted"> Canceled </option><!----></select>

My current code is able to get the collection of dropdown elements but I am not sure how to access the ngModel value of each dropdown. My code is currently:

// Get the collection of Disposition elements
    const dispositionsCompleted = page.locator('select[name="dispo"]');
    // Check that all Dispositions are set to Complete
    const count = await dispositionsCompleted.count();

    for (let i = 0; i < count; i++) {   
        console.log(await dispositionsCompleted.nth(i).locator('option').inputValue());
        
    }

Solution

  • If your list isn't dynamic so you always have the same number of select elements and you don't want to deal with setting different ids for selectors, you can use the :nth-match selector to go trough on the list and check the values line by line.

    Example:

    // wait for the selector
    await page.waitForSelector(':nth-match("select", 0)');
    
    // Check the value
    await expect(page.locator('option[selected="selected"]')).toHaveText("Value");

    A nicer solution:

    await page.waitForSelector("select");
    
    // get all the select
    const dropdowns = await page.$$("select");
    console.log(dropdowns.length);
    console.log(await dropdowns[0].innerText());
    console.log(await dropdowns[1].innerText());
    
    // the expect() comes here

    Playwright :nth-match pseudo selector

    https://playwright.dev/docs/selectors#pick-n-th-match-from-the-query-result