testbench icon indicating copy to clipboard operation
testbench copied to clipboard

Add support for filtering elements by a property

Open mvysny opened this issue 10 months ago • 3 comments

Say I want to find a Dialog with headerTitle xyz. I would like to write $(DialogElement.class).property("headerTitle", "xyz").first().

TestBench 23

mvysny avatar Mar 10 '25 12:03 mvysny

Workaround:

$(DialogElement.class).all().stream()
                .filter(it -> caption.equals(it.getPropertyString("headerTitle")))
                .findFirst()
                .orElseThrow(() -> new java.util.NoSuchElementException("No Dialog with header title " + caption));

mvysny avatar Mar 10 '25 12:03 mvysny

Better workaround:

public class TestBenchUtils {
    private static String getTagName(Class<?> elementClass) {
        Element annotation = elementClass.getAnnotation(Element.class);
        if (annotation == null) {
            return "*";
        }
        return annotation.value();
    }

    public static <T extends TestBenchElement> List<T> findByProperty(HasElementQuery context, Class<T> elementClass, String propertyName, String propertyValue) {
        final String tagName = getTagName(elementClass);
        final TestBenchElement element;
        final String searchScope;
        if (context instanceof TestBenchElement) {
            element = (TestBenchElement) context;
            searchScope = "arguments[0]";
        } else {
            element = null;
            searchScope = "document";
        }
        final List<TestBenchElement> matchingElements = (List<TestBenchElement>) ((HasTestBenchCommandExecutor) context).getCommandExecutor().
                executeScript("var propertyName = arguments[2]; var propertyValue = arguments[3]; var tagName = arguments[1]; return Array.from(" + searchScope + ".querySelectorAll(tagName)).filter(node => node[propertyName] == propertyValue)", element, tagName, propertyName, propertyValue);
        return matchingElements.stream().map(e -> e.wrap(elementClass)).toList();
    }
}

mvysny avatar Mar 25 '25 07:03 mvysny

Is this what has been implemented as withPropertyValue?

Artur- avatar Oct 07 '25 13:10 Artur-