zero_cool
zero_cool

Reputation: 4264

How to get text() of Child Component in Enzyme / React

I've got a childComponent that has text.

I've written a test that is checking for that text. That test passed until I made two notable changes. I need to keep those changes, and get the test to pass.

  1. The component has been refactored to use forwardRef
  2. The childComponent I'm trying to test for text is defined as a property of the parentComponent e.g. parentComponent.childComponent = childComponent

The test works fine when the parentComponent does not use forwardRef

I can see the text in the childComponent when I print the html() of the parent in the console.

HTML:

  <div class="parentComponent">
    <div class="childComponent">
      childText
    </div>
  </div>

parentComponent:

class SelectRef extends PureComponent {
   /// component code here
} 
// Bottom of parentComponent
const Select = forwardRef((props, ref) => <SelectRef {...props} innerRef={ref} />);
Select.displayName = "Select";
Select.Option = Option;

export default Select;

I've tried:

expect(component.dive().text()).to.contain("text");
expect(component.shallow().text()).to.contain("text");
expect(component.prop('children')).to.contain("text");

What are other ways to get the childComponent text in a component using Enyzme / React?

Upvotes: 1

Views: 4945

Answers (1)

zero_cool
zero_cool

Reputation: 4264

Here's a way to do this when using forwardRef:

I have a helper function in the enzyme test that allows you to access the class function in the forwardRef wrapper:

const getComp = (comp, className = "default-class") =>
  comp
    .find("ComponentRef")
    .dive()
    .find(className);

Example test:

  it("should render the place holder text", () => {
      const component = shallow(
        <Component placeholderText="Select an option" selectName="test"/>
      );

      const comp = getComp(component)
      expect(comp.text()).to.contain("inner text of component");
  }); 

Upvotes: 2

Related Questions