ridermansb
ridermansb

Reputation: 11059

How can I retrieve instance of children component

I need access the instance of children component:

const wrapper = shallow(
    <Provider store={store}>
        <CustomForm />
    </Provider>
);

I need to access CustomForm instance .. how can I do this?

I tried:

const instance = wrapper
    .children(0)
    .instance();

Upvotes: 0

Views: 47

Answers (1)

Brian Adams
Brian Adams

Reputation: 45810

If your test needs to access the instances of child components then you will need to use mount() instead of shallow().

shallow() does not do a full DOM rendering and creates an instance for the root element if it is declared using a class (note that functional components never have instances), but it does not create instances for child components.

mount() does a full DOM rendering and creates instances for all components (root or child) declared using classes.

In your example you are using chilren(0) to access the ReactWrapper, alternatives are childAt(0), or something like find('Component').at(0).

Here is a simple working example:

import * as React from 'react';
import { mount } from 'enzyme';

class Component extends React.Component {
  componentMethod = () => 'componentMethod called'

  render() { 
    return (
      <span>The Component</span>
    );
  }
}

test('get component instance', () => {
  const component = mount(
    <div>
      <Component />
    </div>
  );
  const componentInstance = component.find('Component').at(0).instance();
  expect(componentInstance.componentMethod()).toBe('componentMethod called'); // PASSES
});

Upvotes: 1

Related Questions