Skip to content

Commit 0bdab5d

Browse files
committed
fix: Return closest Text matching a query
1 parent 292e883 commit 0bdab5d

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/__tests__/queryByApi.test.js

+27-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ test('queryByText not found', () => {
4848
).toBeFalsy();
4949
});
5050

51-
test('queryByText nested multiple <Text> in <Text>', () => {
51+
test('queryByText nested text across multiple <Text> in <Text>', () => {
5252
expect(
5353
render(
5454
<Text>
@@ -62,6 +62,18 @@ test('queryByText nested multiple <Text> in <Text>', () => {
6262
).toBeTruthy();
6363
});
6464

65+
test('queryByText with nested Text components return the closest Text', () => {
66+
const NestedTexts = () => (
67+
<Text nativeID="1">
68+
<Text nativeID="2">My text</Text>
69+
</Text>
70+
);
71+
72+
const { getByText } = render(<NestedTexts />);
73+
74+
expect(getByText('My text').props.nativeID).toBe('2');
75+
});
76+
6577
test('queryByText nested <CustomText> in <Text>', () => {
6678
const CustomText = ({ children }) => {
6779
return <Text>{children}</Text>;
@@ -75,3 +87,17 @@ test('queryByText nested <CustomText> in <Text>', () => {
7587
).queryByText('Hello World!')
7688
).toBeTruthy();
7789
});
90+
91+
test('queryByText nested deep <CustomText> in <Text>', () => {
92+
const CustomText = ({ children }) => {
93+
return <Text>{children}</Text>;
94+
};
95+
96+
expect(
97+
render(
98+
<Text>
99+
<CustomText>Hello</CustomText> <CustomText>World!</CustomText>
100+
</Text>
101+
).queryByText('Hello World!')
102+
).toBeTruthy();
103+
});

src/helpers/getByAPI.js

+12
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,18 @@ const getChildrenAsText = (children, TextComponent, textContent = []) => {
4444
}
4545

4646
if (child?.props?.children) {
47+
// This means that down in the tree of a <TextComponent /> there's another TextComponent that
48+
// contains a string, but the parent itself doesn't contain any other string
49+
// We should then match against this child, since querying aims to always return the element
50+
// the closest to the target text. For instance in this example we don't want
51+
// getChildrenAsText to match on the Text of nativeID "1", but the one of nativeID "2"
52+
// <Text nativeID="1">
53+
// <Text nativeID="2">My text</Text>
54+
// </Text>
55+
if (filterNodeByType(child, TextComponent) && textContent.length === 0) {
56+
return;
57+
}
58+
4759
getChildrenAsText(child.props.children, TextComponent, textContent);
4860
}
4961
});

0 commit comments

Comments
 (0)