Skip to content

Commit db65dfb

Browse files
authored
feat(breaking): toHaveTextContent supports nested arrays of sibling elements (#52)
BREAKING CHANGE: toHaveTextContent may produce more output in some cases due to including all nested sibling elements
1 parent 7667d5f commit db65dfb

File tree

3 files changed

+20
-8
lines changed

3 files changed

+20
-8
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ expect(queryByTestId('button')).not.toHaveProp('title', 'ok');
243243
toHaveTextContent(text: string | RegExp, options?: { normalizeWhitespace: boolean });
244244
```
245245

246-
Check if an element has the supplied text.
246+
Check if an element or its children have the supplied text.
247247

248248
This will perform a partial, case-sensitive match when a string match is provided. To perform a
249249
case-insensitive match, you can use a `RegExp` with the `/i` modifier.

src/__tests__/to-have-text-content.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -49,17 +49,27 @@ describe('.toHaveTextContent', () => {
4949

5050
test('can handle multiple levels with content spread across descendants', () => {
5151
const { queryByTestId } = render(
52-
<Text testID="parent">
53-
<Text>Step</Text>
54-
<Text> 1 </Text>
52+
<View testID="parent">
53+
<Text>One</Text>
54+
<Text>Two</Text>
5555
<View>
56-
<Text> of </Text>
56+
<Text>Three</Text>
5757
</View>
58-
4
59-
</Text>,
58+
<View>
59+
<Text>Four</Text>
60+
{null}
61+
<Text>Five</Text>
62+
<View>
63+
<Text>Six</Text>
64+
<Text>Seven</Text>
65+
</View>
66+
<Text>Eight</Text>
67+
</View>
68+
Nine
69+
</View>,
6070
);
6171

62-
expect(queryByTestId('parent')).toHaveTextContent('Step 1 of 4');
72+
expect(queryByTestId('parent')).toHaveTextContent('OneTwoThreeFourFiveSixSevenEightNine');
6373
});
6474

6575
test('does not throw error with empty content', () => {

src/to-have-text-content.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ function getText(child, currentValue = '') {
88

99
if (!child) {
1010
return value;
11+
} else if (Array.isArray(child)) {
12+
return child.reduce((acc, element) => acc + getText(path(['props', 'children'], element)), '');
1113
} else if (typeof child === 'object') {
1214
return getText(path(['props', 'children'], child), value);
1315
} else {

0 commit comments

Comments
 (0)