React - 如何测试表单提交?

Joe*_*dee 4 javascript unit-testing reactjs

我有以下React组件:

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>
        );
    }
};
Run Code Online (Sandbox Code Playgroud)

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

此外,正如您所看到的,该doSignupForm函数会触发API调用 - 应该使用集成测试(?)单独测试此API调用.

Car*_*nez 5

您可以使用React Utils模拟表单提交:

var rendered = TestUtils.renderIntoDocument(SignupForm);
var form = TestUtils.findRenderedDOMComponentWithTag(rendered, 'form');
TestUtils.Simulate.submit(form);
Run Code Online (Sandbox Code Playgroud)

此外,测试对实际API的调用是不可靠的,您应该使用您期望的响应来模拟API调用,一个想法是将API调用提取到其自己的模块中,并设置间谍来测试您的行为.具有特定响应的组件(使用Jasmine的示例间谍):

spyOn(apiModule, "requestProjects").and.callFake(function() {
    return { ...someProjects };
});
Run Code Online (Sandbox Code Playgroud)

参考:

https://facebook.github.io/react/docs/test-utils.html https://volaresystems.com/blog/post/2014/12/10/Mocking-calls-with-Jasmine

  • 这是因为在与外部服务交互时,您通常不拥有该代码。如果您的 Internet 连接或服务出现故障,即使您的代码正常,您的测试套件也会失败。另一个因素是它非常慢。您想在受控条件下测试代码的行为。 (2认同)

Joe*_*dee 0

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

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

});
Run Code Online (Sandbox Code Playgroud)