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

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

问题描述

我完全无法尝试测试使用React编写的简单表单,如何知道提交按钮是否有效?经过一番研究后,我认为这样做的方法是制作一个模拟函数,然后检查它是否被调用,但是我敢肯定我做错了。

  onObjSubmit(event){
event.preventDefault()
.....(获取某些内容)
}

render(){
return(
< form id = myForm onSubmit = {event => this.onObjSubmit(event)}>
< input type =文本 id = name />< br />
<输入类型=文本 id = last_name />< br />
<输入类型= submit value = submit>
< / form>
);
}

测试:

  it('Test',()=> {
const包装器=浅(< TestComp />));
const fn =开玩笑。 fn();
wrapper.instance()。onObjSubmit = fn;
wrapper.update();
wrapper.find('#myForm')。simulate('submit');
Expect(fn).toBeCalled();
});

有人可以指出我正确的方向吗?

解决方案

您并不是唯一一个对此感到迷茫的人。 酶问题页面上的该线程提供了许多解决此问题的建议方法。 / p>

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?

解决方案

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天全站免登陆