Skip to content

Commit 49dbb66

Browse files
pierrezimmermannbampierrezimmermann
andauthored
feat: allow getByText and queryByText to find text nested in fragments (#934)
Co-authored-by: pierrezimmermann <[email protected]>
1 parent a010ffd commit 49dbb66

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

src/__tests__/byText.test.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,3 +436,36 @@ describe('Supports normalization', () => {
436436
expect(getByText('A text', { normalizer: normalizerFn })).toBeTruthy();
437437
});
438438
});
439+
440+
test('getByText and queryByText work properly with text nested in React.Fragment', () => {
441+
const { getByText, queryByText } = render(
442+
<Text>
443+
<>Hello</>
444+
</Text>
445+
);
446+
expect(getByText('Hello')).toBeTruthy();
447+
expect(queryByText('Hello')).not.toBeNull();
448+
});
449+
450+
test('getByText and queryByText work properly with text partially nested in React.Fragment', () => {
451+
const { getByText, queryByText } = render(
452+
<Text>
453+
He<>llo</>
454+
</Text>
455+
);
456+
expect(getByText('Hello')).toBeTruthy();
457+
expect(queryByText('Hello')).not.toBeNull();
458+
});
459+
460+
test('getByText and queryByText work properly with multiple nested fragments', () => {
461+
const { getByText, queryByText } = render(
462+
<Text>
463+
He
464+
<>
465+
l<>l</>o
466+
</>
467+
</Text>
468+
);
469+
expect(getByText('Hello')).toBeTruthy();
470+
expect(queryByText('Hello')).not.toBeNull();
471+
});

src/helpers/byText.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,15 @@ const getChildrenAsText = (children, TextComponent) => {
3030
// has no text. In such situations, react-test-renderer will traverse down
3131
// this tree in a separate call and run this query again. As a result, the
3232
// query will match the deepest text node that matches requested text.
33-
if (filterNodeByType(child, TextComponent) && textContent.length === 0) {
33+
if (filterNodeByType(child, TextComponent)) {
3434
return;
3535
}
3636

37-
getChildrenAsText(child.props.children, TextComponent);
37+
if (filterNodeByType(child, React.Fragment)) {
38+
textContent.push(
39+
...getChildrenAsText(child.props.children, TextComponent)
40+
);
41+
}
3842
}
3943
});
4044

0 commit comments

Comments
 (0)