Dom-testing-library: Select element by testRole

Created on 10 Apr 2019  路  3Comments  路  Source: testing-library/dom-testing-library

Describe the feature you'd like:

getByTestId has a really nice implementation and we've adopted using data-test-id in our code for selenium testing and we are now looking at using in unit testing too.
Currently, in our defined testing strategy, we have a component assigned to a data-test-id, but we then have elements within the component defined with a data-test-role attribute.

For example:

export const FilterBox = ({ ariaLabel, onFilter, filter, placeholder, searchButtonString }: FilterBoxProps) => {
    return (
        <div className="data-list-filter-box" data-test-id="filter-box">
            <FontAwesomeIcon icon={faSearch} data-test-role="magnifying-glass-icon" />
            <input
                aria-label={ariaLabel}
                data-test-role='input-box'
                onChange={onFilter}
                placeholder={placeholder}
                type='search'
                value={filter}
            />
            <Button color='primary' data-test-role='search-button'>
                {searchButtonString}
            </Button>
        </div>
    )
}

So it would be useful to link in possibly 2 functions into this awesome library:

  • a function that, similar to getByTestId, will retrieve based on a test role. If it could be configured/overridden like the test Id, that would be ideal.
  • a function that, similar to getByTestId, will accept the test id as the first parameter and a test role as a second parameter.

Suggested implementation:

```
queryAllByTestRole = (container, testRole) => queryHelpers.firstResultOrNull(() => queryHelpers.queryAllByAttribute('data-test-role', container, testRole));

queryAllByTestIdAndRole = (container, testId, testRole) => container.querySelector([data-test-id=\'${testId}\'] [data-test-role=\'${testRole}\']);
``

Describe alternatives you've considered:

I've written my own utility functions based on the existing react-testing-library functions, but it would be cleaner and more maintainable if they were incorporated into the library.

All 3 comments

Definitely think there should be more flexibility allowed when defining data-test selectors.

I really feel like data-testid's should be used as a last resort. Your application should be accessible and you should be using more semantic queries to get your elements.

If you'd like, you can define your own custom queries pretty easily in a custom render method: https://testing-library.com/docs/react-testing-library/api#queries

I'm pretty sure I don't want to add another query for test IDs...

I think in this case you don't need two types of test id, really? It doesn't look like the strings collide. If you want to scope the second query you can use within:

within(getByTestId('filter-box'))
  .getByTestId('search-button')
Was this page helpful?
0 / 5 - 0 ratings