如何在 React 中测试表单提交? [英] How can I test form submit in React?

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

问题描述

我有以下 React 组件:

导出默认类 SignUpForm 扩展 React.Component {...doSignupForm(事件){//一些 API 调用...}使成为() {返回 (<div><form action="/" onSubmit={this.doSignupForm.bind(this)} id="register-form"><button type="submit" id="register_button">注册</button></表单>

);}};

我想测试按钮是否触发了 doSignupForm 函数 - 我该怎么做(最好使用 Mocha/Chai/Enzyme/Sinon)?

此外,如您所见,doSignupForm 函数会触发 API 调用 - 是否应使用集成测试 (?) 单独测试此 API 调用.

解决方案

如前所述 此处,Enzyme 不支持事件冒泡.因此,找到了以下解决方法:

从'sinon'导入sinon;从酶"导入 {mount};从'柴'进口柴;var expect = chai.expect;it('触发表单提交', () => {const doSignupForm = sinon.stub(SignUpForm.prototype, 'doSignupForm').returns(true);const wrapper = mount();wrapper.find('#register_button').get(0).click();期望(doSignupForm).to.have.been.call;doSignupForm.restore();});

I have the following React component:

export default class SignUpForm extends React.Component {
    ...
    doSignupForm(event) {
        // Some API call...
    }

    render() {
        return (
            <div>
                <form action="/" onSubmit={this.doSignupForm.bind(this)} id="register-form">
                    <button type="submit" id="register_button">Sign Up</button>
                </form>
            </div>
        );
    }
};

I want to test that the button fires the doSignupForm function - how do I do this (ideally using Mocha/Chai/Enzyme/Sinon)?

In addition, as you can see the doSignupForm function fires an API call - should this API call be tested seperately using an integration test (?).

解决方案

As stated here, event bubbling is not supported in Enzyme. Therefore, found the following workaround:

import sinon from 'sinon';
import {mount} from 'enzyme';
import chai from 'chai';
var expect = chai.expect;

it('fires form submit', () => {
   const doSignupForm = sinon.stub(SignUpForm.prototype, 'doSignupForm').returns(true);

    const wrapper = mount(<SignUpForm />);
    wrapper.find('#register_button').get(0).click();
    expect(doSignupForm).to.have.been.called;
    doSignupForm.restore();

});

这篇关于如何在 React 中测试表单提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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