首页 > 解决方案 > Sinon 使用 Spy 进行表单验证出错

问题描述

我无法验证使用诗浓的Spy()功能是否正确填写了表格。我的目标是通过这个单元测试:

  it('check entire form validation when the form is valid', () => {
     let formSpy = spy();
     const form = mount(<Form isFormValid={formSpy} />);
     form.find('.name').simulate('change', { target: { value: 'sasrank' } });
     form.find('.email').simulate('change', { target: { value: 'aasdbc@xyz.com' } });
     form.find('.phone').simulate('change', { target: { value: '9856756756' } });
     form.find('.url').simulate('change', { target: { value: 'http://google.com' } });
     form.find('.button').simulate('click');
     expect(formSpy.calledWith(true)).toEqual(true);
  });

此表单使用一些基本的 HTML5 验证

Form.js

import React, {Component} from 'react';
import {PropTypes} from 'prop-types';

class Form extends Component {
constructor(props) {
    super(props);
    this.state = {
        isEmailValid: false,
        isNameValid: false,
        isPhoneValid: false,
        isUrlValid: false,
    };

}

render() {
    return (
        <div className="row">
        <h1 className="text-center">Form Validation</h1>
        <form>
            <h3>Name:
            </h3>
            <input type="text" required pattern="[A-Za-z]{3,30}" className="name"></input>
            <h3>Email:
            </h3>
            <input type="email" required className="email"></input>
            <h3>Phone:
            </h3>
            <input type="number" required className="phone"></input>
            <h3>Blog URL:
            </h3>
            <input type="url" required className="url"></input>
            <div className="small-6 small-centered text-center columns">
                <button href="#" className="button success expand round text-center">Verify</button>
            </div>
        </form>
    </div>);
  }
 }

export default Form;

为了通过这个测试,我可以修改什么?

标签: reactjsunit-testingsinonspy

解决方案


你不使用isFormValid任何地方Form。React 不知道如何神奇地isFormValid传递给React.Component构造函数(除非你使用了一些你没有提到的神奇库。

这不是“sinon”,而是缺乏适当的实现来调用isFormValid

至少,您应该onClick在按钮上安装回调并使用一些值调用此验证,如下所示:

<button onClick={this.handleSubmit} ...>Verify</button>

onSubmit看起来或多或少像这样的方法:

onSubmit = (event) => {
    const valuues = collectValues();
    if (this.props.isFormValid(values)) {
        // ... handle submit
    }
}

有很多地方使用表单验证,比如这个答案也使用表单HTML5 验证 API(虽然不确定酶是否支持它)


推荐阅读