Search code examples
c#selenium-webdrivermat-select

How do I select an option from a mat-select?


I have what looks like a dropdown menu, but it is a mat-select. I get an error when my test hits this element which says Element should have been select but was mat-select.

This is the element public DropdownSelect FormDropdown => new(FindElement(By.Id("formDropdown")));

This is my method of trying to select an item in the dropdown.

   public void SelectForm(string form)
        {
            FormDropdown.Click();
            var selectElement = new SelectElement(FormDropdown.Element);
            selectElement.SelectByText(form);
        }

How do I handle this since it appears that I cannot use what I have been using for dropdowns?


Solution

  • I figured out that the SelectElement and SelectByText were not going to work so I just got the XPath for the options in the mat-select and made methods to Click the dropdown and then just click the option.

            public void SelectForm(string formName)
            {
                FormDropdown.Click();
                var option = driver.FindElement(By.XPath($"//span[text()=' {formName} ']"));
                option. Click();
            }
    

    If there is a better way I would be open to exploring it as I have more of these mat-select elements on this form and I would hate to have to define each option for every one of them.