Skip to content

Commit 83b28b2

Browse files
authored
fix: *ByText would call toString() on objects and only match on [object Object] (#290)
1 parent 360a53d commit 83b28b2

File tree

2 files changed

+65
-6
lines changed

2 files changed

+65
-6
lines changed

src/__tests__/queryByApi.test.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// @flow
2+
import React from 'react';
3+
import { Text, Image } from 'react-native';
4+
import { render } from '..';
5+
6+
test('queryByText nested <Image> in <Text> at start', () => {
7+
expect(
8+
render(
9+
<Text>
10+
<Image source={{}} />
11+
Hello
12+
</Text>
13+
).queryByText('Hello')
14+
).toBeTruthy();
15+
});
16+
17+
test('queryByText nested <Image> in <Text> at end', () => {
18+
expect(
19+
render(
20+
<Text>
21+
Hello
22+
<Image source={{}} />
23+
</Text>
24+
).queryByText('Hello')
25+
).toBeTruthy();
26+
});
27+
28+
test('queryByText nested <Image> in <Text> in middle', () => {
29+
expect(
30+
render(
31+
<Text>
32+
Hello
33+
<Image source={{}} />
34+
World
35+
</Text>
36+
).queryByText('HelloWorld')
37+
).toBeTruthy();
38+
});
39+
40+
test('queryByText not found', () => {
41+
expect(
42+
render(
43+
<Text>
44+
Hello
45+
<Image source={{}} />
46+
</Text>
47+
).queryByText('SomethingElse')
48+
).toBeFalsy();
49+
});

src/helpers/getByAPI.js

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,10 @@ const filterNodeByName = (node, name) =>
1818
const getNodeByText = (node, text) => {
1919
try {
2020
// eslint-disable-next-line
21-
const { Text, TextInput } = require('react-native');
21+
const { Text } = require('react-native');
2222
const isTextComponent = filterNodeByType(node, Text);
2323
if (isTextComponent) {
24-
const textChildren = React.Children.map(
25-
node.props.children,
26-
// In some cases child might be undefined or null
27-
child => (child !== undefined && child !== null ? child.toString() : '')
28-
);
24+
const textChildren = getChildrenAsText(node.props.children);
2925
if (textChildren) {
3026
const textToTest = textChildren.join('');
3127
return typeof text === 'string'
@@ -39,6 +35,20 @@ const getNodeByText = (node, text) => {
3935
}
4036
};
4137

38+
const getChildrenAsText = children => {
39+
return React.Children.map(children, child => {
40+
if (typeof child === 'string') {
41+
return child;
42+
}
43+
44+
if (typeof child === 'number') {
45+
return child.toString();
46+
}
47+
48+
return '';
49+
});
50+
};
51+
4252
const getTextInputNodeByPlaceholder = (node, placeholder) => {
4353
try {
4454
// eslint-disable-next-line

0 commit comments

Comments
 (0)