diff --git a/src/__tests__/queryByApi.test.js b/src/__tests__/queryByApi.test.js index 5ca5a06cc..f7f39b991 100644 --- a/src/__tests__/queryByApi.test.js +++ b/src/__tests__/queryByApi.test.js @@ -48,21 +48,60 @@ test('queryByText not found', () => { ).toBeFalsy(); }); -test('queryByText nested multiple in ', () => { +test('queryByText nested text across multiple in ', () => { + const { queryByText } = render( + + Hello{' '} + + World + !{true} + + + ); + + 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 ', () => { + const CustomText = ({ children }) => { + return {children}; + }; + expect( render( - Hello{' '} - - World - !{true} - + Hello World! ).queryByText('Hello World!') ).toBeTruthy(); }); -test('queryByText nested in ', () => { +test('queryByText nested deep in ', () => { const CustomText = ({ children }) => { return {children}; }; @@ -70,7 +109,7 @@ test('queryByText nested in ', () => { expect( render( - Hello World! + Hello World! ).queryByText('Hello World!') ).toBeTruthy(); diff --git a/src/helpers/getByAPI.js b/src/helpers/getByAPI.js index 723cc20e5..18409d052 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); } });