Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spy method in react component

My component has a method ..

onUpdateProperty = (key, value) => {
  this.state.formData[key] = value;
}

I want to test if after change input, this method is called...

it('on update input should update formData', function () {
  const wrapper = mount(<MyComp.wrappedComponent {...this.minProps} />);
  const spy = spyOn(wrapper.instance(), 'onUpdateProperty');

  expect(spy).not.toHaveBeenCalled();

  const nameInput = wrapper.find('[name="name"]');
  nameInput.simulate('change', {
    target: { name: 'name', value: 'v1' },
  });

  wrapper.update();

  // expect(spy).toHaveBeenCalledWith('name', 'v1');
  expect(spy).toHaveBeenCalled();
});  

wrappedComponent is because I use Mobx-react

like image 629
ridermansb Avatar asked Jul 05 '26 04:07

ridermansb


1 Answers

My advice is to not spy of internal functions of your component but just test the state.

expect(wrapper.state.formData.name).toBe('v1)

if you really want to spy on it you have to spy on the prototype of you component.

jest.spyOn(MyComp.wrappedComponent.prototype, 'onUpdateProperty')
like image 83
Andreas Köberle Avatar answered Jul 08 '26 13:07

Andreas Köberle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!