用玩笑和酶在 React 中测试一个表单 [英] Test a form in React with jest and enzyme

查看:29
本文介绍了用玩笑和酶在 React 中测试一个表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全无法测试用 React 制作的简单表单,我怎么知道提交按钮是否有效?经过一些研究,我认为这样做的方法是制作一个模拟函数,然后检查它是否被调用,但我很确定我做错了.

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>
  );
}

和测试:

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?

推荐答案

您不是唯一一个对此感到迷茫的人.Enzyme 问题页面上的此主题 提供了许多解决此问题的建议方法.

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.

这篇关于用玩笑和酶在 React 中测试一个表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆