Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test event handlers Using enzyme

Tags:

jestjs

enzyme

How do we test the click handlers using shallow render using enzyme

class Example extends React.Component {
  render() {
    const {
      message
    } = this.props
    return <Alert key={message.id} bsStyle={message.state} onDismiss={()=>this.handleAlertDismiss(message.id)}>{message.text}</Alert>
  }
  handleAlertDismiss = (id) = > {
    console.log(id)
  }
}

how do we test the onDismiss function that was added to the Alert component.

like image 280
Kamaraju Avatar asked Oct 17 '22 22:10

Kamaraju


1 Answers

Create the component and call the dismiss function like this.

const log = jest.fn();
global.console = {log}
example = shallow(<Example message={{id: 'test'}}/>); 
example.props('onDismiss')() //just find the dismiss prop and call the function
expect(log).toHaveBeenCalledWith('test')

The problem with your example is that there is nothing real to test. To make it work with your console.log example I mock console.log with a spy, that can be tested to check it was called with the correct parameter.

like image 144
Andreas Köberle Avatar answered Oct 21 '22 07:10

Andreas Köberle