0
votes

I'm trying to write tests for my Reactjs application ( I'm very new to testing this ), but I can't seem to grasp how it works properly. Below is my Component, what I want to test is handleRegisterFieldClick(). I've seen examples of mocking a click function but since the function I need to call is one passed from a parent component, how can I simulate that? I want to check if state.class = 'clickedSquare' after calling handleRegisterFieldClick().

export default class Square extends Component {
constructor(props) {
  super(props)
  this.state = {
    fieldcell: props.field,
    value: props.value,
    class: props.class,
    xPos: props.xPos,
    yPos: props.yPos,
    clicked: props.clicked
  }
  this.handleClick = this.handleClick.bind(this);
  this.handleRegisterFieldClick = this.handleRegisterFieldClick.bind(this);
}

handleClick() {
  if(this.state.fieldcell){
    if (this.props.clicked) {
      this.setState({
        class: 'square'
      })
    } else {
      this.setState({
        class: 'clickedSquare'
      })
    }
  }
}

handleRegisterFieldClick(){
  if(this.state.fieldcell){
    this.handleClick()
    var params = { 
      xPos: this.state.xPos,
      yPos: this.state.yPos
    }
    this.props.registerFieldClick(params)
  }
}



render() {

  return (
    <button className={this.state.class} onClick={this.handleRegisterFieldClick}  background={this.state.backgroundcolor}>
      {this.state.value !== 0 ? this.state.value : null}
    </button>
  );
}

}

1
Target the button, simulate click, then check the class name on the button? What have you tried? Can you also share your unit test code? - Drew Reese

1 Answers

0
votes

Perhaps something like this

const timeout = 'some value';
const timeout2 = 'some other value';

  componentDidMount() {
    setTimeout(() => {
      this.handleRegisterFieldClick();
      setTimeout(() => {
        //Since setState is asynchronous were using a second timeout
        //check the state.class condition here.
      }, timeout2);
    }, timeout);
  }