From 56151bab03ab7571ac824f8f88d439cf5e9c441b Mon Sep 17 00:00:00 2001 From: Jeroen Vannevel Date: Tue, 28 Apr 2020 22:34:49 +0100 Subject: [PATCH] Fixed an issue where xByText would call toString() on objects and only match on `[object Object]` --- src/__tests__/queryByApi.test.js | 49 ++++++++++++++++++++++++++++++++ src/helpers/getByAPI.js | 22 ++++++++++---- 2 files changed, 65 insertions(+), 6 deletions(-) create mode 100644 src/__tests__/queryByApi.test.js diff --git a/src/__tests__/queryByApi.test.js b/src/__tests__/queryByApi.test.js new file mode 100644 index 000000000..7d453cfce --- /dev/null +++ b/src/__tests__/queryByApi.test.js @@ -0,0 +1,49 @@ +// @flow +import React from 'react'; +import { Text, Image } from 'react-native'; +import { render } from '..'; + +test('queryByText nested in at start', () => { + expect( + render( + + + Hello + + ).queryByText('Hello') + ).toBeTruthy(); +}); + +test('queryByText nested in at end', () => { + expect( + render( + + Hello + + + ).queryByText('Hello') + ).toBeTruthy(); +}); + +test('queryByText nested in in middle', () => { + expect( + render( + + Hello + + World + + ).queryByText('HelloWorld') + ).toBeTruthy(); +}); + +test('queryByText not found', () => { + expect( + render( + + Hello + + + ).queryByText('SomethingElse') + ).toBeFalsy(); +}); diff --git a/src/helpers/getByAPI.js b/src/helpers/getByAPI.js index b0bf792ad..ecc0e31d9 100644 --- a/src/helpers/getByAPI.js +++ b/src/helpers/getByAPI.js @@ -18,14 +18,10 @@ const filterNodeByName = (node, name) => const getNodeByText = (node, text) => { try { // eslint-disable-next-line - const { Text, TextInput } = require('react-native'); + const { Text } = require('react-native'); const isTextComponent = filterNodeByType(node, Text); if (isTextComponent) { - const textChildren = React.Children.map( - node.props.children, - // In some cases child might be undefined or null - child => (child !== undefined && child !== null ? child.toString() : '') - ); + const textChildren = getChildrenAsText(node.props.children); if (textChildren) { const textToTest = textChildren.join(''); return typeof text === 'string' @@ -39,6 +35,20 @@ const getNodeByText = (node, text) => { } }; +const getChildrenAsText = children => { + return React.Children.map(children, child => { + if (typeof child === 'string') { + return child; + } + + if (typeof child === 'number') { + return child.toString(); + } + + return ''; + }); +}; + const getTextInputNodeByPlaceholder = (node, placeholder) => { try { // eslint-disable-next-line