Skip to content

Commit c8395ef

Browse files
marchenk0vaMariia Marchenkovathymikee
authored
feat: query nested text nodes (#293)
* feat: query nested text nodes * test on nested text nodes * test on custom component, refactor * remove comments * move textContent out of module scope, fixup children check Co-authored-by: Mariia Marchenkova <marchewka@Mariias-MacBook-Pro.local> Co-authored-by: Michał Pierzchała <thymikee@gmail.com>
1 parent 53dc00a commit c8395ef

File tree

3 files changed

+49
-210
lines changed

3 files changed

+49
-210
lines changed

src/__tests__/queryByApi.test.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,31 @@ test('queryByText not found', () => {
4747
).queryByText('SomethingElse')
4848
).toBeFalsy();
4949
});
50+
51+
test('queryByText nested multiple <Text> in <Text>', () => {
52+
expect(
53+
render(
54+
<Text>
55+
Hello{' '}
56+
<Text>
57+
World
58+
<Text>!{true}</Text>
59+
</Text>
60+
</Text>
61+
).queryByText('Hello World!')
62+
).toBeTruthy();
63+
});
64+
65+
test('queryByText nested <CustomText> in <Text>', () => {
66+
const CustomText = ({ children }) => {
67+
return <Text>{children}</Text>;
68+
};
69+
70+
expect(
71+
render(
72+
<Text>
73+
Hello <CustomText>World!</CustomText>
74+
</Text>
75+
).queryByText('Hello World!')
76+
).toBeTruthy();
77+
});

src/helpers/getByAPI.js

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ const getNodeByText = (node, text) => {
2121
const { Text } = require('react-native');
2222
const isTextComponent = filterNodeByType(node, Text);
2323
if (isTextComponent) {
24-
const textChildren = getChildrenAsText(node.props.children);
24+
const textChildren = getChildrenAsText(node.props.children, Text);
2525
if (textChildren) {
2626
const textToTest = textChildren.join('');
2727
return typeof text === 'string'
@@ -35,18 +35,24 @@ const getNodeByText = (node, text) => {
3535
}
3636
};
3737

38-
const getChildrenAsText = children => {
39-
return React.Children.map(children, child => {
38+
const getChildrenAsText = (children, TextComponent, textContent = []) => {
39+
React.Children.forEach(children, child => {
4040
if (typeof child === 'string') {
41-
return child;
41+
textContent.push(child);
42+
return;
4243
}
4344

4445
if (typeof child === 'number') {
45-
return child.toString();
46+
textContent.push(child.toString());
47+
return;
4648
}
4749

48-
return '';
50+
if (child?.props?.children) {
51+
getChildrenAsText(child.props.children, TextComponent, textContent);
52+
}
4953
});
54+
55+
return textContent;
5056
};
5157

5258
const getTextInputNodeByPlaceholder = (node, placeholder) => {

0 commit comments

Comments
 (0)