jeudi 23 juin 2016

React testing components with children components

I recently started developing components with React, and now that things start looking good, I want to test them using Mocha and Enzyme.

Here is my proposition/question/request for answer:

I have a Fieldset component which contains a "title" props and other components (several Field components) which I pass using {this.props.children) like the following:

Component:

export default class Fieldset extends React.Component {
  constructor(props) {
      super(props);
  }

  render() {
    return (
      <fieldset>
         <p>{this.props.title || ""}</p>
         {this.props.children}
      </fieldset>
   );
 }
}

Use:

<Fieldset title="Log In">
    <Field
      label={<Label text="username" />}
      input={
        <TextInput
          fieldName="username"
          type="text"
          placeholder="Enter your username"
          state={this.props.state}
          handleChange={this.props.handleInputChange}
        />
      }
    />
    <Field
      label={<Label text="password" />}
      input={
        <TextInput
          fieldName="password"
          type="password"
          placeholder="Enter your password"
          state={this.props.state}
          handleChange={this.props.handleInputChange}
        />
      }
    />

Test:

I already made a few tests which work such as

describe('<Fieldset />', () => {
  let wrapper;

  beforeEach(() => {
     wrapper = mount(
        <Fieldset
           title="My title"
        />
     )
  });

  it('should have a type variable in the props', () => {
     expect(wrapper.props().title).to.equal('My title');
  });

Questions:

1) Is it a good practice to use components as props of other components like "input={ [TextInput title="blabla"] } ?

2) How do I test the behavior of {this.props.children} in my Test ?

a: Should I use something like that and not worry too much with node except making sure that it's equal to the content of my node variable ?

   const node = <div>Hi</div>

   beforeEach(() => {
      wrapper = mount(
         <Fieldset
            title="My title"
            {node}
      />
    )
   });

b: Should I import the other components (in this case the Field component) with mock props and so on (like a real use of the component with children) and use it to test the Fieldset component ? Would not I be out of context for the purpose of this Fieldset test ?

<Fieldset title="Log In">
    <Field
      label={<Label text="my label" />}
      input={
        <TextInput
          fieldName="username"
          type="text"
          * etc etc * 
        />
    />
 </Fieldset>

Thank you for helping me finding out which way is the best to test my components.

Aucun commentaire:

Enregistrer un commentaire