react-test-renderer findAllByProps returns duplicate results for RN components
See original GitHub issueIs this a bug report?
Yes
Have you read the Contributing Guidelines?
Yes
Environment
Environment: OS: macOS Sierra 10.12.6 Node: 8.4.0 Yarn: 1.0.2 npm: 5.3.0 Watchman: 4.9.0 Xcode: Xcode 8.3.3 Build version 8E3004b Android Studio: 2.3 AI-162.4069837
Packages: (wanted => installed) react: ^16.0.0 => 16.0.0 react-native: ^0.49.3 => 0.49.3 react-test-renderer ^16.0.0 => 16.0.0
Target Platform: Node (testing using Jest)
Steps to Reproduce
(Reproducible repo below)
- Use
react-test-renderer
inside of ajest
test to render a singleView
with atestID
- Use the renderer’s
findAllByProps
method to search for thattestID
Expected Behavior
findAllByProps
returns 1 instance, the View
that was rendered
Actual Behavior
findAllByProps
returns 2 instances, the View
that was rendered and a child of that View
with all of the same props.
Reproducible Demo
https://github.com/TAGraves/react-test-renderer-bug-example
Notes
I’m trying to use some of the new utilities provided by react-test-renderer
to make assertions against a RN component hierarchy, but unfortunately the way RN mocks components when using Jest makes this a futile attempt. findAllByProps
is returning twice as many elements as it should. I’ve attached a super simple example at the top (rendering just a single <View />
but getting two results from findAllByProps).
The issue stems from mockComponent.js. When it mocks a component out, its render returns another component with the same name and props. So if your intended tree looks like:
<View testID="a">
<SomeComponent />
</View>
the outputted tree will be:
<View testID="a">
<View testID="a">
<SomeComponent />
</View>
</View>
I believe this can be fixed by changing the mocked implementation just to:
const Component = class extends RealComponent {
render() {
return this.props.children || null;
}
};
and I am happy to submit a PR with this change, but would like some guidance on if there’s a reason for the existing approach before I go changing things.
Thank you!
Issue Analytics
- State:
- Created 6 years ago
- Reactions:4
- Comments:8
Top GitHub Comments
Facing the same issue with latest version, quite frustrating indeed.
Did anybody find a workaround?
Edit: My workaround is instead to use findAll and filter also by type, like this:
const elements = component.root.findAll(n => n.props.testID === 'id' && n.type === 'Text')
Hope it helps.
+1 I just encountered this issue as well