( queryNames: QueryNames, matcherFn: (prop: P, value: M) => boolean ) => (instance: ReactTestInstance) => { - const getBy = (matcher: M) => { + const filterWithName = ( + node: ReactTestInstance, + options: QueryOptions, + matcher: M + ) => { + const matchesRole = + isNodeValid(node) && matcherFn(node.props[name], matcher); + + return ( + matchesRole && !!getQueriesForElement(node).queryByText(options.name) + ); + }; + + const getBy = (matcher: M, queryOptions?: QueryOptions) => { try { + if (queryOptions?.name) { + return instance.find((node) => + filterWithName(node, queryOptions, matcher) + ); + } + return instance.find( (node) => isNodeValid(node) && matcherFn(node.props[name], matcher) ); @@ -44,10 +97,18 @@ const makeA11yQuery =
( } }; - const getAllBy = (matcher: M) => { - const results = instance.findAll( - (node) => isNodeValid(node) && matcherFn(node.props[name], matcher) - ); + const getAllBy = (matcher: M, options?: QueryOptions) => { + let results = []; + + if (options?.name) { + results = instance.findAll((node) => + filterWithName(node, options, matcher) + ); + } else { + results = instance.findAll( + (node) => isNodeValid(node) && matcherFn(node.props[name], matcher) + ); + } if (results.length === 0) { throw new ErrorWithStack( @@ -59,28 +120,50 @@ const makeA11yQuery =
( return results; }; - const queryBy = (matcher: M) => { + const queryBy = (matcher: M, options?: QueryOptions) => { try { - return getBy(matcher); + return getBy(matcher, options); } catch (error) { return createQueryByError(error, queryBy); } }; - const queryAllBy = (matcher: M) => { + const queryAllBy = (matcher: M, options?: QueryOptions) => { try { - return getAllBy(matcher); + return getAllBy(matcher, options); } catch (error) { return []; } }; - const findBy = (matcher: M, waitForOptions?: WaitForOptions) => { - return waitFor(() => getBy(matcher), waitForOptions); + const findBy = ( + matcher: M, + queryOptions?: QueryOptions & WaitForOptions, + waitForOptions?: WaitForOptions + ) => { + const deprecatedWaitForOptions = warnDeprectedWaitForOptionsUsage( + queryOptions + ); + + return waitFor(() => getBy(matcher, queryOptions), { + ...deprecatedWaitForOptions, + ...waitForOptions, + }); }; - const findAllBy = (matcher: M, waitForOptions?: WaitForOptions) => { - return waitFor(() => getAllBy(matcher), waitForOptions); + const findAllBy = ( + matcher: M, + queryOptions?: QueryOptions & WaitForOptions, + waitForOptions?: WaitForOptions + ) => { + const deprecatedWaitForOptions = warnDeprectedWaitForOptionsUsage( + queryOptions + ); + + return waitFor(() => getAllBy(matcher, queryOptions), { + ...deprecatedWaitForOptions, + ...waitForOptions, + }); }; return {