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

Co-authored-by: pierrezimmermann <pierrez@nam.tech>
This commit is contained in:
Pierre Zimmermann
2022-03-25 10:24:05 +01:00
committed by GitHub
parent a010ffdbca
commit 49dbb66f8e
2 changed files with 39 additions and 2 deletions
+33
View File
@@ -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();
});
+6 -2
View File
@@ -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)
);
}
}
});