3

我的组件有一个方法..

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

我想测试更改输入后是否调用此方法...

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是因为我使用 Mobx-react

4

1 回答 1

8

我的建议是不要监视组件的内部功能,而只是测试state.

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

如果您真的想监视它,则必须监视组件的原型。

jest.spyOn(MyComp.wrappedComponent.prototype, 'onUpdateProperty')
于 2017-04-30T14:06:01.960 回答