vendredi 21 juillet 2017

How to test React component class methods

I have a React component that I am attempting to test some of its instance methods, but I am having trouble understanding how I am supposed to do it. The issue that is tripping me up is the fact that I am referring to this.setState() in the test and also event.target which are within a different context in my tests and therefore come back as undefined. What is the correct way to handle this?

Here is my component:

export default class MessageForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      message: '',
    };
  }

  onChange(event) { // testing this method
    const message = event.target.value; // event is undefined
    this.setState(prevState => Object.assign({}, prevState, { message })); // 'this' is undefined
  }

  handleOnClick(event) {
    event.preventDefault();
    // do some stuff here
  }

  render() {
    return (
      <Form action="post">
        <TextArea onChange={this.onChange} />
        <ExpireButtonGroup />
        <SubmitButton onClick={this.handleOnClick}>
          <LockIcon src={lock} />
          Save
        </SubmitButton>
      </Form>
    );
  }
}

I am using Jest and Enzyme for testing. I am able to trigger the method using this test:

 test('it should allow a message to be typed', () => {
    const messageForm = shallow(<MessageForm />);
    expect(messageForm.instance().onChange())
  });

Aucun commentaire:

Enregistrer un commentaire