使用Jest和Enzyme反应模拟提交表单功能

时间:2020-06-02 23:57:49

标签: reactjs jestjs enzyme

我试图创建一个“简单”测试来检查表单的onSubmit函数是否已添加/未从组件中删除。 表单组件:

<form onSubmit={SubmitForm} data-test="submit-new-product-form" >
<TextField type="text" ref={enteredNameRef} className="text-field" label="Name" value={enteredName} onChange={event =>  { handleChange('enteredName', setEnteredName, event.target.value) } } data-test="input-entered-name" /></form>

测试示例:

test('should call submitNewProduct function upon form submission', () => {
  let submitNewProduct = jest.fn(); //This is the mock I'm trying to put to check if it was called  
  let wrapper = shallow(<AddNewProduct />);
  let form = wrapper.find("[data-test='submit-new-product-form']");  

  //This is where things don't make sense to me. Above I have the form component and I need to assign the 
  //submitNewProduct mock function to its onSubmit prop. But I don't know how.
  
  form.simulate('submit', { preventDefault: () => console.log('preventDefault') });

  expect(submitNewProduct).toHaveBeenCalled();
});

有什么想法吗?

0 个答案:

没有答案