React - 如何测试表单提交? [英] React - how to test form submit?

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

问题描述

我有以下React组件:

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

我想测试该按钮是否会触发 doSignupForm 功能 - 我该怎么做(理想情况下使用Mocha / Chai / Enzyme / Sinon)?

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

此外,你可以看到 doSignupForm 函数触发API调用 - 如果使用集成测试(?)单独测试此API调用。

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

推荐答案

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

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