Skip to content

Preferred way to simulate clicks on children? #1411

@ffxsam

Description

@ffxsam

I have a component that's structured like so:

  // inside render()
    return <div style={styles.root} onMouseLeave={this.mouseLeave}>
      <Button
        label={label}
        onClick={this.buttonClick}
        {...other}
      />

      {this.state.clickedOnce ? warning : null}
    </div>

I understand that with snapshot testing, I could test the props exposed by my component like this:

  tree.props.onMouseLeave();
  tree = component.toJSON();
  expect(tree).toMatchSnapshot();

But what if I wanted to trigger an onClick on the Button? I tried this in my test:

  tree.children[0].props.onClick();
  tree = component.toJSON();
  expect(tree).toMatchSnapshot();

And it seems to work fine. Is there a better way? I also had to modify my onClick handler:

  buttonClick({ nativeEvent: event }) {
    if (!this.state.clickedOnce) {
      this.setState({ clickedOnce: true });
    } else {
      if (!this.props.catastrophic || event.shiftKey) {
        this.setState({ clickedOnce: false });
        this.props.onConfirm && this.props.onConfirm();
      }
    }
  }

Jest didn't like trying to access event.nativeEvent, which I think I had in place because I was having some issues accessing event.shiftKey otherwise. But I switched the function signature to just be buttonClick(event) and it seems to work fine.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions