enzyme: Get doesn't always return a react element
the get method for mounted components doesn’t always return a react element even though it says it does. if i create something with nested components, like this,
let el = (
<Parent><Child /></Parent>
);
let wrapper = mount(el);
console.log(wrapper.get(0)); //Parent Component instance, not element
console.log(typeof wrapper.get(0)); //object, not reactelement
console.log(wrapper.find(Child).get(0)); //Child component instance, not element
console.log(typeof wrapper.find(Child).get(0)); //object, not reactelement
is there a way to get the element?
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Comments: 28 (18 by maintainers)
ah got it. that’s good to know. i guess this isn’t a big deal then. the documentation should just change to reflect that it’s not necessarily a reactelement being returned
i think it was related to trying to match against a component with a method for a prop. i got it to work by passing in the actual method on the component that i was matching against.
@ljharb so yeah, it does work, but so does passing the component instance
get
does not return aReactElement
, it returns an instance of the component that exists at the passed index. You can see a failing test case here: enzyme-test-repo/blob/issue-497/test.jsget
relies ongetWrappedComponent
fromReactWrapperComponent
component._instance
(which is returned in either case) is not aReactElement
, it’s an instance of the component that is being rendered. If you want the actualReactElement
then you need to use the internal instance which is available on_reactInternalInstance
(SeeReactInstanceMap
) which holds a reference to the element at_currentElement
.IMO
get()
should not be returning theReactElement
. If you need access to the actualReactElement
then you can access it viaWe should just update the docs so it doesn’t claim to return a
ReactElement
, which it’s never done AFAIK.ah sorry. you’re right about about the typeof.
isValidElement returns false in both scenarios above. it only happens on mount though. not shallow.
here’s the parent class for reference.
and here’s what i passed to mount