Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enzyme, How to access a component passed in props

Tags:

reactjs

enzyme

What I am trying to test in MyComponent is the value of checked props of the Switch component which is a props of FormControlLabel component:

class MyComponent extends Component {

 (...)

 render() {
  return (
   <FormControlLabel
    name={`formControl`}
    control={
      <Switch
        name={`switch`}
        data
        checked={this.state.isChecked}
        onClick={this.handleChange}
        value={checked}
        />
    }
    />
  );
 }
}

I can access the FormControlLabel component like this:

const wrapper = shallow(<MyComponent />);

wrapper.find('[name="formControl"]');

I tried to access the Switch component like this but it's not working:

wrapper.find('[name="switch"]');

How can I access the checked props of Switch component ?

API
  • shallow
Version
  • Enzyme: 3.3.0
  • React: 16.2.0
Adapter
  • enzyme-adapter-react-16
like image 648
Bertrand P Avatar asked May 24 '18 09:05

Bertrand P


People also ask

How do you access a component props when it is rendered?

The child component uses the props argument to know what to render. Now, we can pass a function to the props object. You see we passed a function () => [ "nnamdi", "chidume" ] to ChildComponent via name ,then it can access it by referencing it as key in the props argument: this.props.name .

Can we pass component as a prop?

You can pass a component as props in React by using the built-in children prop. All elements you pass between the opening and closing tags of a component get assigned to the children prop. Copied!


1 Answers

Well, I just found a solution:

expect(wrapper.find('[name="formControl"]').prop('control').props.checked).toEqual(true);
like image 139
Bertrand P Avatar answered Oct 22 '22 07:10

Bertrand P