11import type { ReactTestInstance } from 'react-test-renderer' ;
2- import { TextMatch } from '../matches' ;
32import { matchStringProp } from '../helpers/matchers/matchStringProp' ;
3+ import { TextMatch } from '../matches' ;
4+ import { getQueriesForElement } from '../within' ;
45import { makeQueries } from './makeQueries' ;
56import type {
67 FindAllByQuery ,
@@ -11,14 +12,31 @@ import type {
1112 QueryByQuery ,
1213} from './makeQueries' ;
1314
15+ type ByRoleOptions = {
16+ name ?: TextMatch ;
17+ } ;
18+
19+ const matchAccessibleNameIfNeeded = (
20+ node : ReactTestInstance ,
21+ name ?: TextMatch
22+ ) => {
23+ if ( name == null ) return true ;
24+
25+ const { queryAllByText, queryAllByLabelText } = getQueriesForElement ( node ) ;
26+ return (
27+ queryAllByText ( name ) . length > 0 || queryAllByLabelText ( name ) . length > 0
28+ ) ;
29+ } ;
30+
1431const queryAllByRole = (
1532 instance : ReactTestInstance
16- ) : ( ( role : TextMatch ) => Array < ReactTestInstance > ) =>
17- function queryAllByRoleFn ( role ) {
33+ ) : ( ( role : TextMatch , options ?: ByRoleOptions ) => Array < ReactTestInstance > ) =>
34+ function queryAllByRoleFn ( role , options ) {
1835 return instance . findAll (
1936 ( node ) =>
2037 typeof node . type === 'string' &&
21- matchStringProp ( node . props . accessibilityRole , role )
38+ matchStringProp ( node . props . accessibilityRole , role ) &&
39+ matchAccessibleNameIfNeeded ( node , options ?. name )
2240 ) ;
2341 } ;
2442
@@ -34,12 +52,12 @@ const { getBy, getAllBy, queryBy, queryAllBy, findBy, findAllBy } = makeQueries(
3452) ;
3553
3654export type ByRoleQueries = {
37- getByRole : GetByQuery < TextMatch > ;
38- getAllByRole : GetAllByQuery < TextMatch > ;
39- queryByRole : QueryByQuery < TextMatch > ;
40- queryAllByRole : QueryAllByQuery < TextMatch > ;
41- findByRole : FindByQuery < TextMatch > ;
42- findAllByRole : FindAllByQuery < TextMatch > ;
55+ getByRole : GetByQuery < TextMatch , ByRoleOptions > ;
56+ getAllByRole : GetAllByQuery < TextMatch , ByRoleOptions > ;
57+ queryByRole : QueryByQuery < TextMatch , ByRoleOptions > ;
58+ queryAllByRole : QueryAllByQuery < TextMatch , ByRoleOptions > ;
59+ findByRole : FindByQuery < TextMatch , ByRoleOptions > ;
60+ findAllByRole : FindAllByQuery < TextMatch , ByRoleOptions > ;
4361} ;
4462
4563export const bindByRoleQueries = (
0 commit comments