How to test inner functions defined on Stateless Components in React with Enzyme

Question

I'm using enzyme to test my react components. I have a stateless component that has an inner function. How can i call and test that inner function?

Here is my component:

const Btn = (props) => {
  const types = ['link', 'plainLink', 'primary', 'secondary', 'danger', 'info'];

  const handleClick = (event) => {
    event.preventDefault();
    props.onClick(event);
  };

  return (
    <button onClick={handleClick} className={classes}>
      <span>{props.children}</span>
    </button>
  );
};

I've tried the following, but get an error saying: TypeError: undefined is not a constructor

const btnComp = shallow(<Btn />);
btnComp.instance().handleClick();

Show source
| javascript   | reactjs   | function   | testing   | enzyme   2017-01-05 12:01 1 Answers

Answers to How to test inner functions defined on Stateless Components in React with Enzyme ( 1 )

  1. 2017-01-05 16:01

    I usually test this functionality by setting a sinon.spy for the event:

    const click = sinon.spy();
    const btnComp = shallow(<Btn onClick={click} />);
    
    btnComp.find('button').simulate('click');
    
    expect(click.called).to.equal(true);
    

    Now, you know that the inner function did indeed invoke the props.onClick event, which is the most important bit of its work.

Leave a reply to - How to test inner functions defined on Stateless Components in React with Enzyme

◀ Go back