Test a form in React with jest and enzyme

橙三吉。 提交于 2020-06-15 10:22:50

问题


I'm totally lost trying to test a simple form made with React, how do I know if the submit button is working? After some research I thought that the way to do it is to make a mock function and then check if it was called but I'm pretty sure I'm doing it completely wrong.

onObjSubmit(event){
event.preventDefault()
..... (fetch something)
}

render(){
  return (
    <form id="myForm" onSubmit={event => this.onObjSubmit(event)}>
     <input type="text" id="name" /><br />
     <input type="text" id="last_name" /><br />
     <input type="submit" value="submit">
    </form>
  );
}

And the test:

it('Test', () => {
  const wrapper = shallow(<TestComp />);
  const fn = jest.fn();
  wrapper.instance().onObjSubmit = fn;
  wrapper.update();
  wrapper.find('#myForm').simulate('submit');
  expect(fn).toBeCalled();
});

Can someone please point me in the right direction?


回答1:


You're not the only one who feels lost with this one. This thread on Enzyme's issues page has a lot of suggested approaches to solving this problem.



来源:https://stackoverflow.com/questions/47316691/test-a-form-in-react-with-jest-and-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!