0
votes

I'm learning some react + testing with jest, I have a component which has three numeric inputs and a button. It's a simple calculator with the multiply operation only.

Don't worry about the rest of the code, I'm just trying to simulate the click that performs the operation (in this case it will call a mocked function as shown in the test)

This is the test

function setup() {
    const component = shallow(<Multiplier />);

    return {
       component: component,
       button: component.find('#multiplyButton')
    }
}

describe('Given a Multiplier instantiated', () => {
   it('The button perform operation should invoke the click method', () => {
       const { button } = setup();
       const handleClick = jest.fn();
       button.onclick = handleClick;
       button.simulate('onClick');
       expect(handleClick).toBeCalled();
   });
});

I think the button.onclick assignment is wrong, I tried with prototype and ecma6 Object.assign but it was the same result, the test fails.

I mocked the onclick button with jest.fn(), once the button is pressed it should call this method, but it's always telling me:

Given a Multiplier instantiated › The button perform operation should invoke the click method expect(jest.fn()).toBeCalled()

Any ideas on how to solve this?

1

1 Answers

0
votes

In your example, button is ShallowWrapper and you cant set onclick like there. You should pass mock function to onClick button prop. And I prefer to test only the public API of the component, because a private method is an implementation detail that should be hidden to the users of the component.

// Your component
const MyButton = ({ label, onClick }) => (
  <button type='button' onClick={onClick}>{label}</button>
)

// Your test
describe('<MyButton/>', () => {
  test('should call onClick callback', () => {
    const onClick = jest.fn();
    const wrapper = shallow(<MyButton onClick={onClick}/>);
    wrapper.simulate('click');
    expect(onClick).toHaveBeenCalled();
  });
});