mirror of
https://github.com/callstack/react-native-testing-library.git
synced 2026-09-18 23:09:04 +08:00
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>
This commit is contained in:
committed by
GitHub
parent
53dc00acc9
commit
c8395ef947
@@ -47,3 +47,31 @@ test('queryByText not found', () => {
|
||||
).queryByText('SomethingElse')
|
||||
).toBeFalsy();
|
||||
});
|
||||
|
||||
test('queryByText nested multiple <Text> in <Text>', () => {
|
||||
expect(
|
||||
render(
|
||||
<Text>
|
||||
Hello{' '}
|
||||
<Text>
|
||||
World
|
||||
<Text>!{true}</Text>
|
||||
</Text>
|
||||
</Text>
|
||||
).queryByText('Hello World!')
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
test('queryByText nested <CustomText> in <Text>', () => {
|
||||
const CustomText = ({ children }) => {
|
||||
return <Text>{children}</Text>;
|
||||
};
|
||||
|
||||
expect(
|
||||
render(
|
||||
<Text>
|
||||
Hello <CustomText>World!</CustomText>
|
||||
</Text>
|
||||
).queryByText('Hello World!')
|
||||
).toBeTruthy();
|
||||
});
|
||||
|
||||
+12
-6
@@ -21,7 +21,7 @@ const getNodeByText = (node, text) => {
|
||||
const { Text } = require('react-native');
|
||||
const isTextComponent = filterNodeByType(node, Text);
|
||||
if (isTextComponent) {
|
||||
const textChildren = getChildrenAsText(node.props.children);
|
||||
const textChildren = getChildrenAsText(node.props.children, Text);
|
||||
if (textChildren) {
|
||||
const textToTest = textChildren.join('');
|
||||
return typeof text === 'string'
|
||||
@@ -35,18 +35,24 @@ const getNodeByText = (node, text) => {
|
||||
}
|
||||
};
|
||||
|
||||
const getChildrenAsText = children => {
|
||||
return React.Children.map(children, child => {
|
||||
const getChildrenAsText = (children, TextComponent, textContent = []) => {
|
||||
React.Children.forEach(children, child => {
|
||||
if (typeof child === 'string') {
|
||||
return child;
|
||||
textContent.push(child);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof child === 'number') {
|
||||
return child.toString();
|
||||
textContent.push(child.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
return '';
|
||||
if (child?.props?.children) {
|
||||
getChildrenAsText(child.props.children, TextComponent, textContent);
|
||||
}
|
||||
});
|
||||
|
||||
return textContent;
|
||||
};
|
||||
|
||||
const getTextInputNodeByPlaceholder = (node, placeholder) => {
|
||||
|
||||
Reference in New Issue
Block a user