Skip to content

feat: allow getByText and queryByText to find text nested in fragments #934

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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