diff --git a/docs/API.md b/docs/API.md index 6e4f87094..01c7b7de5 100644 --- a/docs/API.md +++ b/docs/API.md @@ -50,6 +50,8 @@ type ReactTestInstance = { A method returning a `ReactTestInstance` with matching text – may be a string or regular expression. Throws when no matches. +This method will join `` siblings to find matches, similarly to [how React Native handles these components](https://facebook.github.io/react-native/docs/text#containers). This will allow for querying for strings that will be visually rendered together, but may be semantically separate React components. + ### `getAllByText: (text: string | RegExp)` A method returning an array of `ReactTestInstance`s with matching text – may be a string or regular expression. diff --git a/src/__tests__/render.test.js b/src/__tests__/render.test.js index aa884840d..211847acb 100644 --- a/src/__tests__/render.test.js +++ b/src/__tests__/render.test.js @@ -135,6 +135,38 @@ test('getByText, queryByText', () => { expect(() => queryByText(/fresh/)).toThrow('Expected 1 but found 3'); }); +test('getByText, queryByText with children as Array', () => { + const BananaCounter = ({ numBananas }) => ( + There are {numBananas} bananas in the bunch + ); + + const BananaStore = () => ( + + + + + + ); + + const { getByText } = render(); + + const { toJSON } = render(); + expect(toJSON()).toMatchInlineSnapshot(` + + There are + 3 + bananas in the bunch + +`); + + const threeBananaBunch = getByText('There are 3 bananas in the bunch'); + expect(threeBananaBunch.props.children).toEqual([ + 'There are ', + 3, + ' bananas in the bunch', + ]); +}); + test('getAllByText, queryAllByText', () => { const { getAllByText, queryAllByText } = render(); const buttons = getAllByText(/fresh/i); diff --git a/src/helpers/getByAPI.js b/src/helpers/getByAPI.js index a2fd7fd02..91b131a08 100644 --- a/src/helpers/getByAPI.js +++ b/src/helpers/getByAPI.js @@ -17,12 +17,20 @@ const getNodeByText = (node, text) => { try { // eslint-disable-next-line const { Text, TextInput } = require('react-native'); - return ( - (filterNodeByType(node, Text) || filterNodeByType(node, TextInput)) && - (typeof text === 'string' - ? text === node.props.children - : text.test(node.props.children)) - ); + const isTextComponent = + filterNodeByType(node, Text) || filterNodeByType(node, TextInput); + if (isTextComponent) { + const textChildren = React.Children.map(node.props.children, child => + child.toString() + ); + if (textChildren) { + const textToTest = textChildren.join(''); + return typeof text === 'string' + ? text === textToTest + : text.test(textToTest); + } + } + return false; } catch (error) { throw createLibraryNotSupportedError(error); }