Skip to content

Commit

Permalink
feat: allow getByText and queryByText to find text nested in fragments (
Browse files Browse the repository at this point in the history
#934)

Co-authored-by: pierrezimmermann <[email protected]>
  • Loading branch information
pierrezimmermannbam and pierrezimmermann authored Mar 25, 2022
1 parent a010ffd commit 49dbb66
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
33 changes: 33 additions & 0 deletions src/__tests__/byText.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -436,3 +436,36 @@ describe('Supports normalization', () => {
expect(getByText('A text', { normalizer: normalizerFn })).toBeTruthy();
});
});

test('getByText and queryByText work properly with text nested in React.Fragment', () => {
const { getByText, queryByText } = render(
<Text>
<>Hello</>
</Text>
);
expect(getByText('Hello')).toBeTruthy();
expect(queryByText('Hello')).not.toBeNull();
});

test('getByText and queryByText work properly with text partially nested in React.Fragment', () => {
const { getByText, queryByText } = render(
<Text>
He<>llo</>
</Text>
);
expect(getByText('Hello')).toBeTruthy();
expect(queryByText('Hello')).not.toBeNull();
});

test('getByText and queryByText work properly with multiple nested fragments', () => {
const { getByText, queryByText } = render(
<Text>
He
<>
l<>l</>o
</>
</Text>
);
expect(getByText('Hello')).toBeTruthy();
expect(queryByText('Hello')).not.toBeNull();
});
8 changes: 6 additions & 2 deletions src/helpers/byText.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,15 @@ const getChildrenAsText = (children, TextComponent) => {
// 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) {
if (filterNodeByType(child, TextComponent)) {
return;
}

getChildrenAsText(child.props.children, TextComponent);
if (filterNodeByType(child, React.Fragment)) {
textContent.push(
...getChildrenAsText(child.props.children, TextComponent)
);
}
}
});

Expand Down

0 comments on commit 49dbb66

Please sign in to comment.