mercredi 29 janvier 2020

React - functional component, test if a function is called onChange (with Jest and Enzyme)

I have a simple functional component which I need to test.

const Product = () => {
    const handleOnChange = (value) => {
        console.log(value);
    }

    return (
        <div>
            <input type="text" onChange={(e) => {handleOnChange(e.target.value)}} />
        </div>
    )
}

I'd like to test if "handleOnChange" function is called when the input changes its value. I tried that:

let wrapper;
beforeEach(() => {
    wrapper = shallow(<Product />);
});
describe('Product interactions', () => {
it('should call handleOnChange function on input change', () => {

  const mockedhandleOnChange = jest.fn(); 
  wrapper.handleOnChange = mockedhandleOnChange;
  wrapper.find('input').simulate('change', {target: {value: 10}});
  expect(mockedhandleOnChange).toHaveBeenCalledTimes(1);    
});

});

Of course it doesn't work as I cannot reach the function via "wrapper.handleOnChange".

Please help!

Aucun commentaire:

Enregistrer un commentaire