Skip to content

fix: Return closest Text matching a query #489

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 7 commits into from
Aug 16, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
28 changes: 27 additions & 1 deletion src/__tests__/queryByApi.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ test('queryByText not found', () => {
).toBeFalsy();
});

test('queryByText nested multiple <Text> in <Text>', () => {
test('queryByText nested text across multiple <Text> in <Text>', () => {
expect(
render(
<Text>
Expand All @@ -62,6 +62,18 @@ test('queryByText nested multiple <Text> in <Text>', () => {
).toBeTruthy();
});

test('queryByText with nested Text components return the closest Text', () => {
const NestedTexts = () => (
<Text nativeID="1">
<Text nativeID="2">My text</Text>
</Text>
);

const { getByText } = render(<NestedTexts />);

expect(getByText('My text').props.nativeID).toBe('2');
});

test('queryByText nested <CustomText> in <Text>', () => {
const CustomText = ({ children }) => {
return <Text>{children}</Text>;
Expand All @@ -75,3 +87,17 @@ test('queryByText nested <CustomText> in <Text>', () => {
).queryByText('Hello World!')
).toBeTruthy();
});

test('queryByText nested deep <CustomText> in <Text>', () => {
const CustomText = ({ children }) => {
return <Text>{children}</Text>;
};

expect(
render(
<Text>
<CustomText>Hello</CustomText> <CustomText>World!</CustomText>
</Text>
).queryByText('Hello World!')
).toBeTruthy();
});
12 changes: 12 additions & 0 deletions src/helpers/getByAPI.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ const getChildrenAsText = (children, TextComponent, textContent = []) => {
}

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

getChildrenAsText(child.props.children, TextComponent, textContent);
}
});
Expand Down