Skip to content

Commit

Permalink
feat(breaking): toHaveTextContent supports nested arrays of sibling e…
Browse files Browse the repository at this point in the history
…lements (testing-library#52)

BREAKING CHANGE: toHaveTextContent may produce more output in some cases due to including all nested sibling elements
  • Loading branch information
philipbulley authored Mar 2, 2021
1 parent 7667d5f commit db65dfb
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ expect(queryByTestId('button')).not.toHaveProp('title', 'ok');
toHaveTextContent(text: string | RegExp, options?: { normalizeWhitespace: boolean });
```

Check if an element has the supplied text.
Check if an element or its children have the supplied text.

This will perform a partial, case-sensitive match when a string match is provided. To perform a
case-insensitive match, you can use a `RegExp` with the `/i` modifier.
Expand Down
24 changes: 17 additions & 7 deletions src/__tests__/to-have-text-content.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,17 +49,27 @@ describe('.toHaveTextContent', () => {

test('can handle multiple levels with content spread across descendants', () => {
const { queryByTestId } = render(
<Text testID="parent">
<Text>Step</Text>
<Text> 1 </Text>
<View testID="parent">
<Text>One</Text>
<Text>Two</Text>
<View>
<Text> of </Text>
<Text>Three</Text>
</View>
4
</Text>,
<View>
<Text>Four</Text>
{null}
<Text>Five</Text>
<View>
<Text>Six</Text>
<Text>Seven</Text>
</View>
<Text>Eight</Text>
</View>
Nine
</View>,
);

expect(queryByTestId('parent')).toHaveTextContent('Step 1 of 4');
expect(queryByTestId('parent')).toHaveTextContent('OneTwoThreeFourFiveSixSevenEightNine');
});

test('does not throw error with empty content', () => {
Expand Down
2 changes: 2 additions & 0 deletions src/to-have-text-content.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ function getText(child, currentValue = '') {

if (!child) {
return value;
} else if (Array.isArray(child)) {
return child.reduce((acc, element) => acc + getText(path(['props', 'children'], element)), '');
} else if (typeof child === 'object') {
return getText(path(['props', 'children'], child), value);
} else {
Expand Down

0 comments on commit db65dfb

Please sign in to comment.