diff --git a/src/__tests__/queryByApi.test.js b/src/__tests__/queryByApi.test.js index 5ca5a06c..f7f39b99 100644 --- a/src/__tests__/queryByApi.test.js +++ b/src/__tests__/queryByApi.test.js @@ -48,18 +48,43 @@ test('queryByText not found', () => { ).toBeFalsy(); }); -test('queryByText nested multiple in ', () => { - expect( - render( - - Hello{' '} - - World - !{true} - +test('queryByText nested text across multiple in ', () => { + const { queryByText } = render( + + Hello{' '} + + World + !{true} - ).queryByText('Hello World!') - ).toBeTruthy(); + + ); + + expect(queryByText('Hello World!')?.props.nativeID).toBe('1'); +}); + +test('queryByText with nested Text components return the closest Text', () => { + const NestedTexts = () => ( + + My text + + ); + + const { queryByText } = render(); + + expect(queryByText('My text')?.props.nativeID).toBe('2'); +}); + +test('queryByText with nested Text components each with text return the lowest one', () => { + const NestedTexts = () => ( + + bob + My text + + ); + + const { queryByText } = render(); + + expect(queryByText('My text')?.props.nativeID).toBe('2'); }); test('queryByText nested in ', () => { @@ -75,3 +100,17 @@ test('queryByText nested in ', () => { ).queryByText('Hello World!') ).toBeTruthy(); }); + +test('queryByText nested deep in ', () => { + const CustomText = ({ children }) => { + return {children}; + }; + + expect( + render( + + Hello World! + + ).queryByText('Hello World!') + ).toBeTruthy(); +}); diff --git a/src/helpers/getByAPI.js b/src/helpers/getByAPI.js index 723cc20e..18409d05 100644 --- a/src/helpers/getByAPI.js +++ b/src/helpers/getByAPI.js @@ -44,6 +44,14 @@ const getChildrenAsText = (children, TextComponent, textContent = []) => { } if (child?.props?.children) { + // Bail on traversing text children down the tree if current node (child) + // has no text. In such situations, react-test-renderer will traverse down + // this tree in a separate call and run this query again. As a result, the + // query will match the deepest text node that matches requested text. + if (filterNodeByType(child, TextComponent) && textContent.length === 0) { + return; + } + getChildrenAsText(child.props.children, TextComponent, textContent); } });